2017-04-24 96 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