<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()方法就一直循環下去了