124

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

5 Answers 5

265

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

4
  • 1
    What if simply "echo $object->$property_name" is used without the quotes. Seems to be working, but is it for newer php versions only?
    – Yasen
    Mar 10, 2015 at 14:01
  • 4
    @Larry In the OP's case the quotes are needed because $t is the name of property, not a variable containing the name of the property. Mar 13, 2015 at 16:26
  • 2
    Four years later I've realized that I misread @Lamy comment. You're exactly right, Lamy. If the value of $property_name is the string '$t' then echo $object->$property_name works fine. I've updated my answer. Thanks and apologies! Apr 15, 2019 at 14:47
  • Hello. I could use this answer but only with double quotes, @JordanRunning - are you sure it's right with single quotes? Aug 29, 2020 at 10:44
31

Correct answer (also for PHP7) is:

$obj->{$field}
3
  • What if the variable is only part of the property name? Is there a way to do something like $obj->{"$field".'_id'} for example? Oct 27, 2020 at 16:41
  • 1
    Just discovered this is absolutely possible with $obj->{"{$field}".'id'}. It looks horrible but it 100% works. Oct 27, 2020 at 16:47
  • This answer is totally wrong for the question. Jul 3 at 16:57
20

Have you tried:

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

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

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

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

this works on php 5 and 7

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.