Initialize static members in PHP

醉酒当歌 提交于 2019-12-02 05:55:37

From the docs,

"Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed."

new Person() is not a literal or a constant, so this won't work.

You can use a work-around:

class School {
  public static $Headmaster;
}

School::$Headmaster = new Person();

new Person() is an operation, not a value.

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

http://php.net/static

You can initialise the School class to an object:

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

$school = new School();
$school->Headmaster->ShowQualification();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!