1
我已經實現了基於裝飾器模式的基本代碼狙擊。奇怪的PHP裝飾器模式的輸出
裝飾類:
abstract class HTMLDecorator {
/** @var \ArrayObject */
protected $notes;
public function format(){
$html = '';
foreach ($this->getNodes() as $node)
$html .= "<p>{$node}</p>";
return $html;
}
}
這是基類:
class HTML extends HTMLDecorator{
public function __construct(){
$this->nodes = new \ArrayObject();
}
public function getNodes(){
return $this->nodes;
}
}
現在,這兩個類節點添加到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
爲什麼代碼打印「Block html」兩次?
'$ html = ImageHTML($ thml);'typo? –
錯字修正,謝謝 – manix
調用$ html = ImageHTML($ html);使用從$ html = BlockHTML($ html)獲得的結果;可能導致問題。你可以嘗試將返回的值賦給不同的變量,並在最後組裝它。 – FrozenFire