1

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();
}

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();
}

2 Comments

I must ask - why eval? Why don't you just execute the $code right there?
netcoder and Zenph: Oh! I was not aware of that. Thank you for pointing it out.
1

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.

1 Comment

@Mark: Heh. I have yet to find a use for variables variables. I think is was carried over from the register_globals era or something. Because an array provide similar functionality and a lot more.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.