简体   繁体   English

使用类常量的PHP对象访问

[英]PHP Object access with class constant

Is it possible in PHP to access a member of an object where the name of the member is specified by a class constant? 在PHP中是否可以访问一个对象的成员,其中成员的名称由类常量指定?

Consider this example: 考虑这个例子:

class X{
    const foo = "abc";
}

class Y{
    public $abc;
}

$y = new Y();

$y->X::foo = 23; //This does not work

The parser doesn't accept the last line but this is what I want. 解析器不接受最后一行,但这正是我想要的。 I want to access the field with the name stored in the class constant X::foo . 我想访问存储在类常量X::foo的名称的字段。 Is there a syntax to achieve that? 是否有语法来实现这一目标?

Use variable variables , either via a temp or directly: 通过temp或直接使用变量变量

$name = X::foo;          // Via temp var
$y->$name = 23;          // Access the member by the string's content
var_dump($y->{X::foo});  // Dumps 23

Working sample here . 在这里工作样本

You should write your code like this 你应该写这样的代码

$y->{X::foo} = 23;

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM