Reputation: 747
I want to get a property of an object $class->property
but I don't know the name of the property I will try to attain.
It might be $class->property_one
or it might be class->property_two
.
The information whether it's one or two is stored in a variable, let's call it $var
.
The closest I got is this ${'$class->property_'.$var}
but the problem is PHP seems to think I'm looking for a variable called "$class->property_xxx
", while in fact I want $property from $object.
Thank you for you suggestions!
Upvotes: 1
Views: 139
Reputation: 2617
Try something like
$test_class = new stdClass();
$test_class->property_one = 'p_one';
$test_class->property_two = 'p_two';
$var = 'two';
echo $test_class->{"property_$var"};
Prints 'p_two'
Upvotes: 1
Reputation: 157947
You should follow the manual page about variable variables
.
You can do it like this:
$property = 'property_' . $var;
echo $obj->$property;
or with the so called curly syntax like this:
echo $obj->{'property_' . $var};
Upvotes: 1