简体   繁体   English

PHP访问成员变量使用常量

[英]PHP access member variable using constant

This is an very simplified example of some code that is probably overcoded, but I want to access a class member variable using a class constant and was wondering if there's a simpler syntax than using the $foo->__get below? 这是一些代码的非常简化的示例,可能已被过度编码,但是我想使用类常量访问类成员变量,并且想知道是否有比下面的$ foo-> __ get更简单的语法?

class Foo
{
    const BAR = 'bar';

    private $props = array( self::BAR => 'wee' );

    public function __get($name)
    {
        return $this->props[$name];
    }
}

$foo = new Foo();
echo $foo->__get(Foo::BAR);

This also works: 这也适用:

$foo->{Foo::BAR};

Or implement ArrayAccess , then you can have: 或实现ArrayAccess ,那么您可以:

$foo[Foo::BAR]

But why not access it as $foo->bar ?! 但是为什么不以$foo->bar访问它呢? Are you planning to change that constant a lot or am I missing something here? 您是否打算对该常数进行很多更改,或者我在这里缺少什么?

I think the code looks good, but you could use the constructor to initialize the props array: 我认为代码看起来不错,但是您可以使用构造函数来初始化props数组:

class Foo
{
    const BAR = 'bar';

    private $props;

    public function __construct() {
        $this->props = array( self::BAR => 'wee' );
    }

    public function __get($name)
    {
        return $this->props[$name];
    }
}

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

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