<code><?php abstract class MenuComponent { abstract function add(MenuComponent $component); abstract function remove(MenuComponent $component); abstract function getName(); abstract function displayOperation(); } class MenuComposite extends MenuComponent { private $_items = array(); private $_name = null; function __construct($name) { $this->_name = $name; } function remove(MenuComponent $component){ } function add(MenuComponent $component) { $this->_items[$component->getName()] = $component; } function getName(){ return $this->_name; } public function displayOperation() { static $align = '|'; $align .=''; echo $this->_name, " <br>"; foreach($this->_items as $name=> $item) { echo $align; $item->displayOperation(); } } } class Client { static function displayMenu() { $subMenu1 = new MenuComposite('submenu1'); $subMenu1->add($subMenu1); $subMenu1->displayOperation(); } } Client::displayMenu();</code>
输出是无限循环的
submenu1
|submenu1
|submenu1
...
为什么会这样,第一次递归调用displayOperation()后foreach里面应该是空,就停止了,为什么会无限循环?
<code><?php abstract class MenuComponent { abstract function add(MenuComponent $component); abstract function remove(MenuComponent $component); abstract function getName(); abstract function displayOperation(); } class MenuComposite extends MenuComponent { private $_items = array(); private $_name = null; function __construct($name) { $this->_name = $name; } function remove(MenuComponent $component){ } function add(MenuComponent $component) { $this->_items[$component->getName()] = $component; } function getName(){ return $this->_name; } public function displayOperation() { static $align = '|'; $align .=''; echo $this->_name, " <br>"; foreach($this->_items as $name=> $item) { echo $align; $item->displayOperation(); } } } class Client { static function displayMenu() { $subMenu1 = new MenuComposite('submenu1'); $subMenu1->add($subMenu1); $subMenu1->displayOperation(); } } Client::displayMenu();</code>
输出是无限循环的
submenu1
|submenu1
|submenu1
...
为什么会这样,第一次递归调用displayOperation()后foreach里面应该是空,就停止了,为什么会无限循环?
add 的实现 $this->_items[$component->getName()] = $component;
注意$subMenu1->add($subMenu1);
实例$subMenu1的属性$_items["submenu1"]是他自己本身
$subMenu1
然后无穷下去...
类属性$this->item一直是你实例化传进去的对象,所以,这个displayOperation()方法就一直循环下去了