【发布时间】:2016-04-17 19:05:27
【问题描述】:
我正在尝试为树对象创建一个流畅的界面。
这是我目前所做的一个简化示例:
<?php
class node {
private $childs = array();
private $parent;
public function __construct($parent = null) {
$this->parent = $parent;
}
public function addChild($child) {
$this->childs[] = $child;
return $this;
}
public function createChild() {
return $this->addChild(new node($this));
}
public function setFoo() {
/* do something */
return $this;
}
}
$root = new node();
$root ->addChild((new node($root))
->setFoo()
)->addChild((new node($root))
->setFoo()
);
?>
我想减少创建树的部分。 我想做的是这样的:
$root->createChild()->setFoo();
$root->createChild()->setFoo();
一行。并且无需显式创建新节点实例(就像我在第一个代码中使用 new 运算符所做的那样)。
我的目标是能够创建任意顺序的任何树及其任意程度的节点,而无需在代码中添加分号。
【问题讨论】:
标签: php oop tree fluent-interface