[英]Why can't I set $_SERVER['DOCUMENT_ROOT'] as Attribute?
Why can't I set $_SERVER['DOCUMENT_ROOT']
as attribute? 为什么不能将
$_SERVER['DOCUMENT_ROOT']
为属性? 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;
}
}
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. 顺便说一句,您确定私有是适当的选择,通常需要保护。
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. 因此,您需要像mathroc所说的那样在构造函数中初始化它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.