php: Select object property with a dynamic name ($obj->dynamicNameHere)?

Ultrus
Ultrus used Ask the Experts™
on
I should know this, but here I am. I'm trying to select an object property with a non-static name like this:

<?php
$properties = array('property1','property2','property3');
foreach($properties as $property) {
  print $theObject->[[[$property]]]
}
?>

Open in new window


Any thoughts on how to do that? I know it's probably super simple.

Thanks!!!

Chris
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Hello Chris,

since properties are called without a dollar sign behind the arrow, you can simply use a dollar for a dynamic name. Here an example working for me:
// Defining test class
class test{
    public $variable;
}   
// Creating an instance of it
$testobj = new test();
// preset a value
$testobj->variable = 'Wert 1';
// name the variable, can be a loop or something
$varname = 'variable';
// assigning a new value to the named variable above
$testobj->$varname = 'Wert 2';
// let's see if it works
echo $testobj->variable;

Open in new window

Author

Commented:
acbxyz,
I figured it out. If you respond with "Yes, that looks great!", I'll give your response all the points. ;)

<?php
$properties = array('property1','property2','property3');
foreach($properties as $property) {
  print $theObject->{$property}
}
?>

Open in new window

Commented:
Yes, that looks great! ;-)

If $property is a simple string variable as in this example, you even don't need the curly braces, but you can.

Author

Commented:
Thanks! :D

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial