在定义时对属性进行别名化

时间:2012-04-27 19:39:35

标签: php alias instance-variables

以下代码在PHP 5.3中无效

class DatabaseConfiguration {

    public $development = array("user" => "dev");

    public $production = array("user" => "prod");

    public $default =& $this->development;

}

似乎$default只能用编译时常量初始化。它是在任何PHP文档中声明的吗?可以在不依赖构造函数的情况下$default进行初始化吗?

2 个答案:

答案 0 :(得分:3)

来自PHP documentation

  

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

答案 1 :(得分:2)

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

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);
     }
}