【问题标题】:Get Higher Level Object from Object Array Item从对象数组项中获取更高级别的对象
【发布时间】:2017-04-24 12:35:04
【问题描述】:

我有 2 个类都扩展了一个抽象类。这两个类都有一个名为“content”的私有方法,它是另一个类的项目数组。 一旦我将对象 B 添加到 A 类的“内容”数组中,我需要从项目对象 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(这是 Batman 对象),但在 php 错误日志中我收到错误“Batman 类的对象可以不能转成字符串”

【问题讨论】:

  • 给英雄加一个“伙伴”字段怎么样?毕竟不是所有英雄都通用的?

标签: php class object abstract-class


【解决方案1】:

你必须使用“$this”来添加父亲。 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();

?>

【讨论】:

  • 谢谢 Meffen,我在回答中犯了一个错误,实际上我使用了 $this 而不是 $self 但错误不是那个,而是 $father 声明中的“受保护”。如果父亲是私人的,则会产生错误,受保护的一切都很好。你知道为什么吗?
猜你喜欢
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2015-06-07
相关资源
最近更新 更多