user1848605
user1848605

Reputation: 747

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!

Upvotes: 1

Views: 139

Answers (3)

calcinai
calcinai

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

Adidi
Adidi

Reputation: 5253

$obj->{'property_' . $var};

Upvotes: 1

hek2mgl
hek2mgl

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

Related Questions