2

The following code isn't valid in PHP 5.3

class DatabaseConfiguration {

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

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

    public $default =& $this->development;

}

It seems that $default can only be initialized with a compile-time constant. Is it stated in any php doc? Can $default be initialized like this without relying on the constructor?

hakre
  • 193,403
  • 52
  • 435
  • 836
Raffaele
  • 20,627
  • 6
  • 47
  • 86
  • I don't _think_ it can but I'm really curious as to _why_? Can you explain your use-case? I mean, it shouldn't be hard to change PHP so that it _could_ do this, but you probably can't because you _shouldn't_ – Halcyon Apr 27 '12 at 19:41
  • Just wondering. I'm playing with CakePHP and I d prefer not to change the conventions of its db configuration file, which looks exactly like this. Sadly, Cake doesn't seem to have a notion of *environment* (like Rails for example), so it needs a `$default` instance field. Sure, I can implement in the constructor, but I was just looking for the smallest way to accomplish this – Raffaele Apr 27 '12 at 21:36

2 Answers2

4

From the PHP documentation:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
2

You may consider using a method to return the aliased property values…

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);
     }
}
llange
  • 757
  • 2
  • 10
  • 14