2

以下代码在 PHP 5.3 中无效

class DatabaseConfiguration {

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

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

    public $default =& $this->development;

}

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

4

2 回答 2

3

PHP 文档

这个声明可能包括一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且不能依赖于运行时信息才能被评估。

于 2012-04-27T19:42:07.607 回答
2

您可以考虑使用一种方法来返回别名属性值……</p>

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);
     }
}
于 2014-11-08T13:02:41.567 回答