2010-03-01 140 views
1

爲什麼我不能將$_SERVER['DOCUMENT_ROOT']設置爲屬性? 看到示例代碼

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

public function __construct() 
{ 
//code 
} 

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

    } 
} 
+0

你能提供錯誤嗎? – antyrat 2010-03-01 13:47:14

+0

解析錯誤:語法錯誤,第4行test.php中出乎意料的T_VARIABLE – streetparade 2010-03-01 13:50:39

回答

5

在聲明初始化時不能使用其他變量。試試這個:

class foo 
{ 
private $path; 
private $blah; 

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

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

    } 
} 

順便問一下,你確定私人是合適的選擇,經常被保護是可取的。

+0

這不是我所期待的,但是無論如何感謝:-) – streetparade 2010-03-01 13:53:02

2

Class properties只能用常量初始化:

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

所以,你需要初始化它們的構造就像mathroc說。

相關問題