首页 > 解决方案 > 如何在 PHP 中修改类的静态属性?

问题描述

考虑以下代码:

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`.

这在 PHP 中是否可行?

标签: phpoopimmutability

解决方案


您走在正确的轨道上,您只需要以 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

推荐阅读