views:

45

answers:

2
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 :)

+2  A: 

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();
Matthew Flaschen
Your answer being quoted, I understand the "why" part. But *how* should I modify my code so that I can use the classes as described?
Senthil
+1 Thanks :).. Just out of curiosity, how do people live with this? PHP being a widely used language for web development, I am surprised we have to do it this way...
Senthil
A: 

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();
Emil Vikström
Hi, I don't want to instantiate. I just want to use them like Class1::Member1::SubMember.
Senthil
-1. You can't use $this for a static variable.
Lotus Notes