I'm trying to perform the same function dosomething()
to multiple variables $lastsum $avatar $angels $city $square
in PHP.
$lastsum->dosomething();
$avatar->dosomething();
$angels->dosomething();
$city->dosomething();
$square->dosomething();
Is there a way to make this code cleaner by listing the names of the variables in a string array and perform the function with a for loop. I'm looking for something like this. Does anyone know the right way to do this in PHP?
$all = ['lastsum' , 'avatar', 'angels' , 'city' , 'square'];
foreach (....){
$(nameofvariable)->dosomething();
}
What's wrong with
$all = array($lastsum , $avatar, $angels, $city, $square);
foreach (....){
$variable->dosomething();
}
To achieve exactly what you're looking for, use variable variables
$all = array('lastsum' , 'avatar', 'angels' , 'city' , 'square');
foreach ($all as $x) {
$$x->dosomething();
}
Many people consider this to be bad style though.
If you want to use variables variables, it would be more like this:
function dosomething(&$var) {
$var .= 'bar';
}
$a = 'foo';
$b = 'bar';
$vars = array('a', 'b');
foreach ($vars as $var) {
dosomething($$var);
}
var_dump($a); // foobar
var_dump($b); // barbar
If $a
is an object, then you can do $$var->dosomething()
.
EDIT: NOTE: In most cases, if you have to use variables variables, you may want to consider using a proper data structure instead, like an array.
Not an elegant solution. However, you could make use of eval()
:
$all = array( 'lastsum' , 'avatar', 'angels', 'city', 'square' );
foreach ( $all as $var ) {
$code = "\$${var}->dosomething();";
eval($code);
}
Otherwise, store the objects in an array:
$all = array( $lastsum , $avatar, $angels, $city, $square );
foreach ( $all as $obj ) {
$obj->dosomething();
}
Another alternative:
$all = array('lastsum' , 'avatar', 'angels' , 'city' , 'square');
foreach ($all as $x) {
$GLOBALS[$x]->dosomething();
}
Not sure if you could do method calls from the GLOBALS superglobal, but you could most likely access static properties/functions.