简体   繁体   中英

Get property of a class/object dynamically (not knowing the property name beforehand) in PHP

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!

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};
$obj->{'property_' . $var};

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM