2017-04-24 28 views
0

我有兩個類都擴展了一個抽象類。兩個類都有一個名爲「content」的私有方法,它是另一個類的一組項目。 一旦我添加對象B到類AI的「內容」陣列需要從項目目標B. 這裏獲取父對象A爲例子,它更容易來看待它:從對象數組中獲取更高級別的對象項目

<?php 
 

 
abstract class heroes { 
 
    private $tag; 
 
    private $content = array(); 
 
    
 
    function __construct($tag) { 
 
     $this->tag = $tag; 
 
    } 
 
    
 
    public function getContents() { 
 
     return $this->content; 
 
    } 
 
    
 
    protected function addContent($obj) { 
 
     $this->content[] = $obj; 
 
     return $obj; 
 
    } 
 

 
} 
 

 
final class batman extends heroes { 
 

 
    public function addPartner() { 
 
     return $this->addContent(new robin()); 
 
    } 
 
} 
 

 
final class robin extends heroes { 
 

 
    private $capes; 
 
    
 
    public function dieAtFirstFight() { 
 
     return BATMAN OBJ??? 
 
    } 
 
    
 
} 
 

 
$batman = new batman(); 
 
$batman = $batman->addPartner()->dieAtFirstFight(); 
 

 
?>

我試圖在抽象類中添加一個名爲$ father的私有方法,其中每次添加一個夥伴我設置$ self(這是蝙蝠俠對象),但在PHP錯誤日誌中,我得到錯誤「Class of object蝙蝠俠不能轉換爲字符串「

+0

如何畢竟加入了「合作伙伴」字段的英雄是很常見的所有英雄不? – Vini

回答

1

你必須使用」$ t他的「添加父親。在PHP中沒有$ self。

<?php 
 

 
abstract class heroes { 
 
    private $tag; 
 
    private $content = array(); 
 
    protected $father; 
 
    
 
    function __construct($tag) { 
 
     $this->tag = $tag; 
 
    } 
 
    
 
    public function getContents() { 
 
     return $this->content; 
 
    } 
 
    
 
    protected function addContent($obj) { 
 
     $this->content[] = $obj; 
 
     $obj->setFather($this); 
 
     return $obj; 
 
    } 
 
    
 
    protected function setFather($father) { 
 
     $this->father = $father; 
 
    } 
 

 
} 
 

 
final class batman extends heroes { 
 

 
    public function addPartner() { 
 
     return $this->addContent(new robin('tag')); 
 
    } 
 
} 
 

 
final class robin extends heroes { 
 

 
    private $capes; 
 
    
 
    public function dieAtFirstFight() { 
 
     return $this->father; 
 
    } 
 
    
 
} 
 

 
$batman = new batman('tag'); 
 
$batman = $batman->addPartner()->dieAtFirstFight(); 
 

 
?>

+0

謝謝Meffen,我在回答中做了一個錯誤,實際上我使用$ this而不是$ self,但錯誤不是那個,而是$ father聲明中的「protected」。如果父親是私人生成的錯誤,保護一切順利。你知道爲什麼嗎? – prelite