简体   繁体   中英

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?

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:

$foo[Foo::BAR]

But why not access it as $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:

class Foo
{
    const BAR = 'bar';

    private $props;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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