views:

56

answers:

2

Why cant i set $_SERVER['DOCUMENT_ROOT'] as attribute? see example code

class foo
{
private $path = $_SERVER['DOCUMENT_ROOT']; // generates error
private $blah;

public function __construct()
{
//code
}

  public function setBla($bla)
  {
   $this->blah = $bla;

  }
}
+4  A: 

you cannot use other variable when initializing in declaration. try this:

class foo
{
private $path;
private $blah;

public function __construct()
{
$this->$path = $_SERVER['DOCUMENT_ROOT'];
//code
}

  public function setBla($bla)
  {
   $this->blah = $bla;

  }
}

by the way, are you sure private is an appropriate choice, often protected is preferable.

mathroc
That was not what i looked for but thanks anyway :-)
streetparade
+2  A: 

Class properties can only be initialized with constant values:

[…] 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.

So you need to initialize them in the constructor like mathroc said.

Gumbo