Ian
Ian

Reputation: 25336

Stacking Static Classes in PHP

Is there a way to make a static class where it has another static class as a member?

E.G. Parent_Class::Child_Class::Member_function();

Upvotes: 4

Views: 1439

Answers (5)

fijiaaron
fijiaaron

Reputation: 5185

Yes, you can have nested static classes in PHP, but it's not pretty, and it takes a bit of extra work. The syntax is a little different than you have.

The trick is to statically initialize the outer class and create a static instance of the inner class.

You can then do one of two things, both are illustrated below.

  1. refer to a static instance of the inner class (child class is actually a misnomer, because there is no inheritance relationship.)

  2. create a static accessor method for the instance of the inner class (this is preferable because it allows for discovery.)

class InnerClass {
    public static function Member_function() { 
        echo __METHOD__;
    }
}

class OuterClass {
    public static $innerClass;

    public static function InnerClass() {
        return self::$innerClass;
    }

    public static function init() {
        self::$innerClass = new InnerClass();
    }
}
OuterClass::init();

OuterClass::$innerClass->Member_function();
OuterClass::InnerClass()->Member_function();

Upvotes: 1

Lucas Oman
Lucas Oman

Reputation: 15872

No.

However, you could use one of PHP's magic methods to do what you want, perhaps:

class ParentClass {
  public static function __callStatic($method,$args) {
    return call_user_func_array(array('ChildClass',$method),$args);
  }
}

class ChildClass {
  public static function childMethod() {
    ...
  }
}

ParentClass::childMethod($arg);

Upvotes: 1

Jordan Ryan Moore
Jordan Ryan Moore

Reputation: 6887

PHP does not support nested classes in any form (static or otherwise).

Upvotes: 0

Peter Bailey
Peter Bailey

Reputation: 105868

No, classes are not first-class citizens in PHP so they can't be stored in variables.

You could sort of make a pass through function in your outermost class

class Parent_Class
{
    public static $childClass;

    public static function callChildMethod( $methodName, array $args=array() )
    {
        return call_user_func_array( array( self::$childClass, $methodName ), $args );
    }
}

class Child_Class
{
    public static function hello()
    {
        echo 'hello';
    }
}

Parent_Class::$childClass = 'Child_Class';

Parent_Class::callChildMethod( 'hello' );

Upvotes: 0

Will Vousden
Will Vousden

Reputation: 33348

If you mean nested classes, no. I believe they were going to be introduced at one point but ended up getting dropped.

There is namespace support, however, if that's what you're after.

Upvotes: 2

Related Questions