是否可以在 php 中更改构造函数中静态类属性的默认值?
class Test {
public static $property = 'default';
public function __construct() {
self::$property = 'new value';
}
}
上面的代码没有这样做。提前感谢!
编辑
我知道我可以在类外更改值
Test::$property = 'new value';
echo Test::$property;
我想知道我是否可以在类构造函数中做到这一点。
在 PHP 5.3 中,您可以使用后期静态绑定。
在代码中将"self"替换为"static":
class Test {
public static $property = 'default';
public function __construct() {
static::$property = 'new value';
}
}
它会;)工作
你忘了一个双点:
self::$property = 'new value';
这对
我有用。
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;