2017-02-24 89 views
0

如何從父級內創建子對象?從父級內創建子對象?

class Section 
{ 
    protected $url; 
    function __construct($url) 
    { 
     $this->url = $url; 
    } 

    public function createElements() 
    { 

    } 
} 

class ElementA extends Section 
{ 

} 

class ElementB extends Section 
{ 

} 

每個部分將包含多個元素,但是,部分類的全部目的,是創建元素,而不是僅僅存儲與部分數據。

+0

你能不能給我更多的信息,告訴我你想輸出什麼? –

+0

我正在製作一個CMS。 section類是用於「header」,「footer」,「left column」等部分的。變量'$ url'是服務器上爲該部分存儲元素的路徑。元素類是用於元素的,例如'H2','P','FORM'以及許多其他元素。目前,這些元素是在一個以'$ url'作爲參數的靜態函數中產生的。 –

回答

0

你可以做到這一點就像這樣:

public function createElements() 
{ 
    $this->children[] = new ElementA($this->url);  // use $this->url 
    $this->children[] = new ElementB('http://www.google.com'); // or not 
} 
+0

我希望節中的所有元素只有一個Section類的一個實例,否則它會挫敗具有Section類的目的。我不認爲這是可能的,但如果有的話,它肯定會產生更高效的代碼。 –