Stacking static classes in PHP

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

eg. Parent_Class::Child_Class::Member_function();

+3
source share
5 answers

If you mean nested classes, no. I suppose they were about to be introduced at some point, but were eventually dropped.

There is a namespace , however, if you need it.

+2
source

No.

However, you can use one of the magic methods of PHP 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);
+1
source

, PHP, .

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' );
0

PHP ( ).

0

, PHP, , . .

, .

, .

  • ( , ).

  • ( , .)

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

Source: https://habr.com/ru/post/1727548/


All Articles