如何访问在 php 中命名为变量的对象属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3515861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I access an object property named as a variable in php?
提问by Flavio Copes
A Google APIs encoded in JSON returned an object such as this
以 JSON 编码的 Google API 返回了这样的对象
[updated] => stdClass Object
(
[$t] => 2010-08-18T19:17:42.026Z
)
Anyone knows how can I access the $t
value?
任何人都知道我如何访问该$t
值?
$object->$t
obviously returns
$object->$t
显然返回
Notice: Undefined variable:
t
in /usr/local/...Fatal error: Cannot access empty property in /....
注意:未定义变量:
t
在 /usr/local/...致命错误:无法访问 /... 中的空属性。
回答by Jordan Running
Since the name of your property is the string '$t'
, you can access it like this:
由于您的财产的名称是 string '$t'
,您可以像这样访问它:
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
您可以在 repl.it 上看到这两个操作:https://repl.it/@jrunning/SpiritedTroubledWorkspace
回答by Macha
Have you tried:
你有没有尝试过:
$t = '$t'; // Single quotes are important.
$object->$t;
回答by Vacilando
Correct answer (also for PHP7) is:
正确答案(也适用于 PHP7)是:
$obj->{$field}
回答by omarjebari
I'm using php7 and the following works fine for me:
我正在使用 php7,以下对我来说很好用:
class User {
public $name = 'john';
}
$u = new User();
$attr = 'name';
print $u->$attr;
回答by YakovGdl35
this works on php 5 and 7
这适用于 php 5 和 7
$props=get_object_vars($object);
echo $props[$t];