How do I modify static properties of a class in PH

2019-09-20 14:47发布

问题:

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:

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