【问题标题】:How do I modify static properties of a class in PHP?如何在 PHP 中修改类的静态属性?
【发布时间】:2023-04-04 15:20:01
【问题描述】:

考虑以下代码:

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 中是否可行?

【问题讨论】:

  • 如果你使用MyClass::$test = 'bar';而不是MyClass->$test = 'bar'; (你的例子没有使用你在类中分配的静态变量)它返回bar。如果您特别希望我们使用-> 表示法而不是::,它将不起作用(或者,您可能会收到弃用错误)。

标签: php oop immutability


【解决方案1】:

您走在正确的轨道上,您只需将变量作为 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

【讨论】:

  • 太棒了!我忘了我需要在static 属性上使用:: 运算符。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-08-27
  • 1970-01-01
  • 2013-12-16
相关资源
最近更新 更多