2010-03-01 142 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说。

相关问题