How can I access an object property named as a var

2019-01-31 05:18发布

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

4条回答
forever°为你锁心
2楼-- · 2019-01-31 05:49

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

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

$attr = 'name';
print $u->$attr;
查看更多
ら.Afraid
3楼-- · 2019-01-31 05:51

Correct answer (also for PHP7) is:

$obj->{$field}
查看更多
女痞
4楼-- · 2019-01-31 05:55

Have you tried:

$t = '$t'; // Single quotes are important.
$object->$t;
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-31 05:56

This ought to work:

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

Failing that:

$property_name = '$t';
echo $object->{$property_name};
查看更多
登录 后发表回答