到达一个childclass到另一个childclass

Reach a child class to another child class

怎么做?

class A {
     public anyfunction() {};
     /* $B = new B(); */
     /* $C = new C(); */
     /* its defined there */
}

class B extends A {
     function __construct() {
        $this->C->func(); // <---- Showing Error Here
     }
}

class C extends A {
     public function func() {
        echo "Hi";
     }
}

我可以使用 B::func();但我想使用 $this->C->func() 风格

我不确定这里的目标是什么,但在阅读问题后我很好奇并决定试验一下。一个对象可以包含另一个扩展其 class.

的对象
class A {
    // You cannot just do $B = new B(); and $C = new C();.

    // You also cannot have a constructor like this:
    //   public function __construct() {
    //       $this->B = new B;
    //       $this->C = new C;
    //   }
    // because then your constructor becomes recursive and you get an error like:
    // Fatal error: Maximum function nesting level of '256' reached, aborting!

    // So, you have to pass them as constructor arguments.

    public function __construct() {
        // Because an A can have a B, or a C, or both, or neither, the constructor
        // must be written more flexibly.
        foreach (func_get_args() as $obj) {
            $this->{get_class($obj)} = $obj;
        }
    }
}

class B extends A {
     public function __construct() {
        // Because you are calling the method from C in the constructor of B, you 
        // have to invoke the constructor of the parent class first so that your B will 
        // have a C to refer to.
        call_user_func_array('parent::__construct', func_get_args());
        if (property_exists($this, 'C'))
        // Now this works.
        $this->C->func(); // <---- echos 'Hi'
     }
}

class C extends A {
     public function func() {
        echo "Hi";
     }
}

然后你可以构造一个B像:

$B = new B(new C);

它会说

Hi

很奇怪。