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();
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();
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.
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' );
PHP does not support nested classes in any form (static or otherwise).
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);
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.
refer to a static instance of the inner class (child class is actually a misnomer, because there is no inheritance relationship.)
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();