Coder Perfect

In PHP, how can I get access to an object property specified as a variable?

Problem

A JSON-encoded Google API returned an item like this.

[updated] => stdClass Object
(
 [$t] => 2010-08-18T19:17:42.026Z
)

Is there a way to get to the $t value?

$object->$t obviously returns

Asked by Flavio Copes

Solution #1

Because your property’s name is the string ‘$t,’ you can use the following syntax to retrieve it:

echo $object->{'$t'};

Alternatively, you can save the property’s name in a variable and utilize it as follows:

$property_name = '$t';
echo $object->$property_name;

Both of these are demonstrated on Repl.it: https://repl.it/@jrunning/SpiritedTroubledWorkspace

Answered by Jordan Running

Solution #2

The correct solution (which also applies to PHP7) is:

$obj->{$field}

Answered by Vacilando

Solution #3

Have you tried:

$t = '$t'; // Single quotes are important.
$object->$t;

Answered by Macha

Solution #4

I’m using PHP 7, and the following code works perfectly for me:

class User {
    public $name = 'john';
}
$u = new User();

$attr = 'name';
print $u->$attr;

Answered by omarjebari

Solution #5

This is compatible with both PHP 5 and PHP 7.

$props=get_object_vars($object);
echo $props[$t];

Answered by YakovGdl35

Post is based on https://stackoverflow.com/questions/3515861/how-can-i-access-an-object-property-named-as-a-variable-in-php