在PHP中初始化静态成员

时间:2010-05-29 06:39:38

标签: php static-members

class Person {
  public static function ShowQualification() {
  }
}

class School {
  public static $Headmaster = new Person(); // NetBeans complains about this line
}

为什么这不可能?

我希望能够像

一样使用它
School::Headmaster::ShowQualification();

..没有实例化任何类。我该怎么办?

更新:好的,我理解为什么会这样做。有人可以解释这个部分吗?谢谢:))

2 个答案:

答案 0 :(得分:3)

来自the docs

  

“像任何其他PHP静态变量一样,   静态属性可能只是   使用文字或文字初始化   不变;表达式不是   允许“。

new Person()不是文字或常量,所以这不起作用。

您可以使用解决方法:

class School {
  public static $Headmaster;
}

School::$Headmaster = new Person();

答案 1 :(得分:-2)

new Person()是一项操作,而非值。

  

与任何其他PHP静态变量一样,   静态属性可能只是   使用文字或文字初始化   不变;表达式是不允许的。   所以你可以初始化静态   属性为整数或数组(for   例如),你可能不会初始化它   另一个变量,一个函数   返回值,或对象。

http://php.net/static

您可以将School类初始化为对象:

class School {
  public static $Headmaster; // NetBeans complains about this line
  public function __construct() {
    $this->Headmaster = new Person();
  }
}

$school = new School();
$school->Headmaster->ShowQualification();