php - 静态变量的默认值

标签 php static traits

是否可以使用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/

相关文章:

java - 每次返回对象的相同实例

class - 特征B扩展特征A时 "class C extends A with B"和 "class C extends B"有什么区别

php - CakePHP 性能问题 - 30-50 秒的模式加载

java - 如何改变 "private static final"参数?

php - 如何使用CI上传多个文件但只保存一次到数据库?

c++ - C++中静态对象的析构顺序

struct - 结构间共享的方法

generics - 如果我为 B 实现 From<A>,是否也会为 Vec<B> 实现 From<Vec<A>>?

php - 在 laravel 中将文件从 url 上传到 AWS

php - CakePHP updateAll() 不工作