1

Is it possible to simply this code...

echo $object->property1;
echo $object->property2;
echo $object->property3;

... with something like this, with eval ?

for ($i=0; $i<10; $i++)
    echo eval("$object->property".$i);

Thanks.

8
  • Why you didn't defined the property an as array from the first place? Commented May 23, 2013 at 9:36
  • The object is a drupal node, i can't ! Commented May 23, 2013 at 9:37
  • WHY do you want to do this way? What's the purpose? Commented May 23, 2013 at 9:37
  • Why do you need eval() here, using eval() just to reduce 3 lines of code to 2 lines of code at a significant cost in readability, performance overhead and the risk of being eaten by a giant cockroach? Commented May 23, 2013 at 9:37
  • I simplified a lot here, but i've got a loooooooot of code to do for each property[number], and i'd like to put this code in a for loop, to avoid repetitions. Commented May 23, 2013 at 9:39

3 Answers 3

6

You can create the property name dynamically without using eval():

$object = new stdClass();
$object->property1 = 10;
$object->property2 = 20;
$object->property3 = 30;

for ($i=1; $i<4; $i++)
    echo $object->{"property".$i};
Sign up to request clarification or add additional context in comments.

Comments

0

well $object would be out of scope in the eval function. you would need to define the object within the eval string.

Comments

0

Can't you do something like this :

for ($i=0; $i<10; $i++)
{
    $tmp = "$object->property".$i
    echo $$tmp;
}

I'm not sure if dynamic variables are applied that way in OOPhP, I see the downvotes coming :-)

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.