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

PhpJsonGoogle Api

Php Problem Overview


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 /....

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

Correct answer (also for PHP7) is:

$obj->{$field}

Solution 3 - Php

Have you tried:

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

Solution 4 - Php

I'm using php7 and the following works fine for me:

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

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

Solution 5 - Php

this works on php 5 and 7

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlavio CopesView Question on Stackoverflow
Solution 1 - PhpJordan RunningView Answer on Stackoverflow
Solution 2 - PhpVacilandoView Answer on Stackoverflow
Solution 3 - PhpMachaView Answer on Stackoverflow
Solution 4 - PhpomarjebariView Answer on Stackoverflow
Solution 5 - PhpYakovGdl35View Answer on Stackoverflow