How do I modify static properties of a class in PHP?

丶灬走出姿态 提交于 2019-12-13 10:29:34

问题


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


来源:https://stackoverflow.com/questions/53879506/how-do-i-modify-static-properties-of-a-class-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!