PHP有多个子类,可以逐个访问子类


PHP multiple child classes, accessing child class to class

我不完全确定这是理解问题还是语法问题。我正在尝试从同一父级下的其他子类访问子类。

    class TopLevel {
    foreach (glob("assets/php/*.php") as $filename) // will get all .php files within plugin directory
      {
        include $filename;
        $temp = explode('/',$filename);
        $class_name = str_replace('.php','',$temp[count($temp)-1]); // get the class name 
        $this->$class_name = new $class_name;   // initiating all plugins
      }
    }
    class A extends TopLevel {
        $var = 'something';
        public function output() {
            return $this->var;
        }
    }
    class B extends TopLevel {
        // This is where I need help, CAN the child class A be accessed sideways from class B? Obviously they need to be loaded in correct order of dependency.
        $this->A->output();
    }

我不明白为什么这不起作用。不是很好的结构,但它是一个单对象应用程序。

答案是:不,不能从侧面访问子类A。A和B之间没有直接继承。

答案可能是使用类似于这个问题的答案中的函数将$this->A类型转换为类型B的对象:

如何在PHP 中投射对象

将类A的对象放入B中,然后调用A的方法,因为A、B之间没有父子关系。

   $objOfA = new A();
   $objOfA->output();