时间:2021-07-01 10:21:17 帮助过:23人阅读
_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, "
";
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();
输出是无限循环的
submenu1
|submenu1
|submenu1
...
为什么会这样,第一次递归调用displayOperation()后foreach里面应该是空,就停止了,为什么会无限循环?
_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, "
";
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();
输出是无限循环的
submenu1
|submenu1
|submenu1
...
为什么会这样,第一次递归调用displayOperation()后foreach里面应该是空,就停止了,为什么会无限循环?
add 的实现 $this->_items[$component->getName()] = $component;
注意$subMenu1->add($subMenu1);
实例$subMenu1的属性$_items["submenu1"]是他自己本身
$subMenu1
然后无穷下去...
类属性$this->item一直是你实例化传进去的对象,所以,这个displayOperation()方法就一直循环下去了