gpt4 book ai didi

php - 如何在链接类的实例时检索祖先

转载 作者:搜寻专家 更新时间:2023-10-31 21:02:59 25 4
gpt4 key购买 nike

我正在用 PHP 开发一个应用程序,其中(类似 jQuery 的)链接方法样式非常方便。我不是在谈论继承链,而是在谈论彼此“嵌入”的类实例的分类法。现在我想知道如何从较低级别引用较高级别的实例。

这听起来很抽象,所以让我举个例子。假设我想用 PHP 写一本书(proze)(只是为了争论)。如果我能这样编码就非常方便了

$myBestseller = new Book();

$myBestseller
->setAuthor("Jean-Saul Partre")
->addChapter()
->addParagraph("How the Rabit lost its wings.")
->addWords("On a beautiful wintes day, the rabit flew over the … ")
->addWords("Bla bla")
->addWords("Bla bla");

到目前为止,我已经开始工作了。 (我应该包括实际的类定义吗?)现在如果我想引用层次结构中更高层对象的属性怎么办?假设我想在章节的标题中包含作者的名字:

    $myBestseller = new Book();

$myBestseller
->setAuthor("Jean-Saul Partre")
->addChapter()
->addParagrapWithAuthor("How "," fell out of the window.");
->addWords("Bla bla")
->addWords("Bla bla")
->addWords("Bla bla")

var_dump($myBestseller);

我们也在这里添加 Chapter 类定义:

class Chapter{
private $_paragraphs = array();

public function addParagraph($title){
return $this->_pages[] = new Paragraph($title);
}

public function addParagrapWithAuthor($prefix, $suffix){
$author = "Ideo Gram";
return $this->_pages[] = new Paragraph($prefix.$author.$suffix);
}
}

因此,我想使用本书作者的定义,而不是 $author = "Ideo Gram"。带有此代码的标题将是

How Ideo Gram fell out of the window

相反,我想说

How Jean-Saul Patre fell out of the window

这能做到吗?到目前为止,我发现的唯一解决方案是“在 table 底下”传递对后代的引用,但这感觉就像污染了类。

也许答案很直接,但我找不到。我可能不知道正确的条款。::parent,例如,适用于扩展类。

最佳答案

没有魔法。如果您需要 2 个实体之间的双向关系,它们需要相互引用。

因此您的方法 addChapter 可以执行此操作:

public function addChapter() {
return $this->chapters[] = new Chapter($this);
}

所以你的章节变成了:

class Chapter {

protected $book;

public function __construct(Book $book) {
$this->book = $book;
}

....

public function addParagrapWithAuthor($prefix, $suffix){
$author = $this->book->getAuthor()->getFullName();
return $this->_pages[] = new Paragraph($prefix.$author.$suffix);
}
}

关于php - 如何在链接类的实例时检索祖先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com