2015-02-17 50 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();