我正在用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);
我们也可以在这里添加章节类定义:
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” 。这段代码的标题是
Ideo Gram如何脱离窗外
相反,我想说呢
Jean-Saul Patre如何从窗户上掉下来
可以这样做吗?到目前为止,我发现的唯一解决方案是在表格下面传递对后代的引用,但这感觉就像污染了类。
也许答案很直接,但我找不到。我可能不知道正确的条款。例如,parent用于扩展类。
答案 0 :(得分: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);
}
}