How can I access an object property named as a variable in php?

04/20/2020 01:30:02

A Google APIs encoded in JSON returned an object such as this

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

Anyone knows how can I access the $t value?

$object->$t obviously returns

Notice: Undefined variable: t in /usr/local/...

Fatal error: Cannot access empty property in /....

Verified Answer (207 Votes)

08/19/2010 00:28:46

Since the name of your property is the string '$t', you can access it like this:

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

Alternatively, you can put the name of the property in a variable and use it like this:

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

You can see both of these in action on repl.it: https://repl.it/@jrunning/SpiritedTroubledWorkspace

207

Answer #2 (19 Votes)

08/19/2010 00:29:02

Have you tried:

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

Answer #3 (11 Votes)

01/11/2019 00:29:23

Correct answer (also for PHP7) is:

$obj->{$field}
11
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.