2015-02-17 32 views
2

我不完全确定这是一个理解问题或语法。 我正试图从同一父母下的其他子类访问子类。PHP多个子类,访问子类到类

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

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

+1

还有据我可以看到A和B之间没有关系? – PeeHaa 2015-02-17 23:40:14

+0

你也可能想看看[适当的自动加载](http://php.net/manual/en/function.spl-autoload.php),而不是你现在正在做的事情。 – PeeHaa 2015-02-17 23:41:19

+0

您的代码不完整,但如果foreach位于TopLevel类的构造函数中,您要做的工作应该可行。 – Dragony 2015-02-18 00:02:56

回答

0

答案是:不可以,子类A不能横向访问。有A和B

之间没有直接的继承

答案可能是使用功能,如人在回答这个问题类型转换$这个 - >一分为B类型的对象:

How to Cast Objects in PHP

A级
0

制作对象中B,然后调用一个方法是有没有之间的父子关系,B.

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