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
  • Static properties are also called class properties in opposite to object properties. Why would you want to have only one headmaster for all schools? Commented May 29, 2010 at 6:49
  • Please don't look at it semantically. I cannot post my proprietary code. I just thought up some stupid example. Might as well have named them abc and xyz :D Commented May 29, 2010 at 6:54

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

3 Comments

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?
+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: Because it's not the end of the world and it's very little effort?
-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();

2 Comments

Hi, I don't want to instantiate. I just want to use them like Class1::Member1::SubMember.
You can't use $this for a static variable and it doesn't make any sense instantiating an object to access a static variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.