php装饰器模式的奇怪输出
我已经在decorator模式中实现了一个基本的代码片段 装饰类:php装饰器模式的奇怪输出,php,polymorphism,decorator,Php,Polymorphism,Decorator,我已经在decorator模式中实现了一个基本的代码片段 装饰类: abstract class HTMLDecorator { /** @var \ArrayObject */ protected $notes; public function format(){ $html = ''; foreach ($this->getNodes() as $node) $html .= "<p>{$
abstract class HTMLDecorator {
/** @var \ArrayObject */
protected $notes;
public function format(){
$html = '';
foreach ($this->getNodes() as $node)
$html .= "<p>{$node}</p>";
return $html;
}
}
现在,这两个类将节点添加到html数组中
区块:
class BlockHtml extends HTMLDecorator{
protected $html;
public function __construct(HTMLDecorator $html){
$this->html = $html;
}
public function getNodes()
{
$this->html->getNodes()->append('Block html');
return $this->html->getNodes();
}
}
图片:
class ImageHtml extends HTMLDecorator{
protected $html;
public function __construct(HTMLDecorator $html){
$this->html = $html;
}
public function getNodes()
{
$this->html->getNodes()->append('Image html');
return $this->html->getNodes();
}
}
最后,我对它进行了如下测试:
$html = new HTML()
$html = BlockHTML($html);
$html = ImageHTML($html);
echo $html->format();
结果是:
Block html
Image html
Block html
为什么代码会打印“块html”两次 调用
$html=ImageHTML($html)
使用从$html=BlockHTML($html)获得的结果代码>可能是导致问题的原因。您是否可以尝试将返回值分配给不同的变量,并在最后组装它 $html=ImageHTML($thml)代码>输入错误?输入错误已修复,谢谢致电$html=ImageHTML($html);使用从$html=BlockHTML($html)获得的结果;可能是导致问题的原因。您是否可以尝试将返回值赋给不同的变量,并在末尾进行汇编。@FrozenFire,您的话很有意义,因为在另一个getNotes()
类中调用getNodes()
两次填充了我的数组。是的,声明另一个变量可以解决问题!你能把你的评论作为答案吗?好的,我已经把答案贴在这里了。
Block html
Image html
Block html