如果您不选择在构造函数中初始化变量,则只能使用常量值。这里有一个小例子:
define('MY_CONSTANT', 'value');
class MyClass
{
// these will work
private $myVariable = 'constant value';
private $constant = MY_CONSTANT;
private $array = Array('value1', 'value2');
// the following won't work
private $myOtherVariable = new stdClass();
private $number = 1 + 2;
private $static_method = self::someStaticMethod();
public function __construct($param1 = '')
{
$this->myVariable = $param1;
// in here you're not limited
$this->myOtherVariable = new stdClass();
$this->number = 1 + 2;
$this->static_method = self::someStaticMethod();
}
}
查看此手册页以查看允许将哪些值直接分配给属性:http ://php.net/manual/en/language.oop5.properties.php
可能还有更多不同...