在定义时为属性设置别名


Aliasing a property at definition time

以下代码在 PHP 5.3 中无效

class DatabaseConfiguration {
    public $development = array("user" => "dev");
    public $production = array("user" => "prod");
    public $default =& $this->development;
}

似乎$default只能用编译时常量初始化。它在任何 php 文档中都有说明吗?$default可以在不依赖构造函数的情况下像这样初始化吗?

来自 PHP 文档:

此声明可能包括初始化,但 初始化必须是一个常量值,也就是说,它必须能够 在编译时计算,并且不得依赖于运行时 信息以便进行评估。

您可以考虑使用一种方法来返回别名属性值...

class DatabaseConfiguration
{    public $development = array("user" => "dev");
     public $production = array("user" => "prod");
     // Method to define $this->default property as an alias of $this->development
     private function default(){return $this->development;}
     public function __get($name)
     {    if(property_exists($this,$name)){return $this->$name;}
          if(method_exists($this,$name)){return $this->$name();}
          throw new ErrorException('This property does not exist',42,E_USER_WARNING);
     }
}