【问题标题】:Php class and static properties inside constructor构造函数中的 PHP 类和静态属性
【发布时间】:2013-11-08 19:21:47
【问题描述】:

是否可以在php的构造函数中更改静态类属性的默认值?

class Test { 
  public static $property = 'default';

  public function __construct() {
    self::$property = 'new value';
  }       
}

上面的代码没有这样做。 提前致谢!

编辑

我知道我可以在类外更改值

Test::$property = 'new value';
echo Test::$property;

我想知道我是否可以在类构造函数中做到这一点。

【问题讨论】:

  • $a = new Test(); echo Test::$property; 打印new value
  • 您的测试代码应该可以工作,也许您应该发布您的真实代码
  • 你可以考虑使用static::$property,而不是使用self::$property,这样可以更动态地使用:参见:stackoverflow.com/questions/4718808/php-can-static-replace-self

标签: php class properties constructor static


【解决方案1】:

使用 PHP 5.3,您可以使用后期静态绑定。

将代码中的“self”替换为“static”:

class Test { 
  public static $property = 'default';

  public function __construct() {
    static::$property = 'new value';
  }       
}

它会起作用的;)

【讨论】:

  • 是的,它在首先初始化类时工作,但不能直接使用 Test::$property 访问它,这就是 $test = new Test(); 的构造函数; Test::$property 然后它完美地工作:)
  • 我不知道你愿意这样做!因此,您必须为此属性编写一个 getter。
  • 不需要将“self”替换为“static”。示例代码应按描述工作。然而,注意“self”和“static”之间的区别很重要。
【解决方案2】:

你忘了一个双点:

self::$property = 'new value';

【讨论】:

  • 这里只是输入错误
【解决方案3】:

这对我有用。

class Test { 
  public static $property = 'default';
  public function __construct() {
     echo self::$property = 'new value'; // for EXample echo val of property
  }       
}
//When create a new object of class it shows / Assigns value of static property

$test = new Test();
echo Test::$property;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2021-03-07
    相关资源
    最近更新 更多