How do I modify static properties of a class in PH

2019-09-20 14:37发布

Consider the following code:

class MyClass
{

    public static $test = 'foo';

    public function example()
    {
        return Self::$test;
    }

}

// What I'm trying to do
MyClass->$test = 'bar'; 

$test = new MyClass();
echo $test->example(); // Should return `bar` instead of `foo`.

Is this or anything remotely close to this possible in PHP?

1条回答
\"骚年 ilove
2楼-- · 2019-09-20 15:29

You're on the right track you just need to access the variable as Class::$test

class MyClass
{
    public static $test = 'foo';

    public function example()
    {
        return Self::$test;
    }
}

MyClass::$test = 'bar'; 

$test = new MyClass();
echo $test->example(); // returns bar
查看更多
登录 后发表回答