views:

136

answers:

5

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

+1  A: 

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.

Will Vousden
Yeah, I'm basically trying to use static classes in the stead of namespaces; I really hate the \ char as a namespace delimiter.. :P
Ian
A: 

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' );
Peter Bailey
I think what he was talking about was nested types, in the vein of C#:http://msdn.microsoft.com/en-us/library/ms173120(VS.80).aspxThey aren't stored in variables; they're just accessed via their parent classes in a static manner.
Will Vousden
A: 

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

Jordan Ryan Moore
...and why the downvote?
Jordan Ryan Moore
A: 

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);
Lucas Oman
A: 

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