PHP statik üyeleri başlat

2 Cevap php
class Person {
  public static function ShowQualification() {
  }
}

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

Neden bu mümkün değil mi?

Ben gibi bu kullanmak mümkün olmak istiyorum

School::Headmaster::ShowQualification();

.. Herhangi bir sınıf başlatmasını olmadan. Ben bunu nasıl yapabilirim?

Update: Tamam ben NEDEN kısmını anladım. Birisi NASIL kısmını açıklayabilir misiniz? Teşekkürler :)

2 Cevap

Dan 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() bir sabit veya bir sabit değildir, bu yüzden bu iş olmaz.

Bir iş çevresinde kullanabilirsiniz:

class School {
  public static $Headmaster;
}

School::$Headmaster = new Person();

new Person() bir işlem değil, bir değerdir.

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

Bir nesneye Okulu sınıf ilklendirebilirsiniz:

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

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