是否可以使用Traits
为静态变量提供默认值?考虑以下示例。
trait Properties {
public static $properties = [];
}
class Base {
use Properties;
}
Base::$properties[0] = 'val1';
Base::$properties[1] = 'val2';
Base::$properties[2] = 'val3';
class Derived extends Base {
use Properties;
}
Derived::$properties[1] = 'changed value';
Derived::$properties[3] = 'new value';
var_dump(Base::$properties);
var_dump(Derived::$properties);
我希望输出类似于
array (size=3)
0 => string 'val1' (length=4)
1 => string 'val2' (length=4)
2 => string 'val3' (length=4)
array (size=4)
0 => string 'val1' (length=4)
1 => string 'changed value' (length=13)
2 => string 'val3' (length=4)
3 => string 'new value' (length=9)
该示例不起作用,因为 Base 和 Properties 在 Derived 的组合中定义了相同的属性 ($properties)
。如果我从 Derived
中删除 use Properties
,则 Base
和 的
,任何更改都适用于这两个类。我希望通过在两个类中包含 $properties
变量是相同的>派生Properties
来解决这个问题。有什么好的方法可以实现我想要的吗?我不必使用 Traits
,我只是认为这会有所帮助。
最佳答案
我建议采用非常简单的面向对象风格。 它没有特征,但用方法访问器代替属性访问器:
class Base {
private static $properties;
public static function getProperties() {
if (!isset(self::$properties)) {
self::$properties = ['val1', 'val2', 'val3']; // use `array('val1', 'val2', 'val3')` with PHP<5.4
}
return self::$properties;
}
}
class Derived extends Base {
private static $properties; // has nothing to do with parent::$properties!
public static function getProperties() {
if (!isset(self::$properties)) {
self::$properties = parent::getProperties();
self::$properties[1] = 'changed value';
self::$properties[] = 'new value';
}
return self::$properties;
}
}
var_dump(Base::getProperties());
var_dump(Derived::getProperties());
请注意,使用方法访问器从外部修改内部数组不存在任何风险,并且使用具有内存功能的方法实际上不会对性能产生影响。
关于php - 静态变量的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27464014/