Initialize static members in PHP

2019-02-28 23:30发布

问题:

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

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

Why is this not possible?

I want to be able to use this like

School::Headmaster::ShowQualification();

..without instantiating any class. How can I do it?

Update: Okay I understood the WHY part. Can someone explain the HOW part? Thanks :)

回答1:

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();


回答2:

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();