根據這個原理,我們就可以實現DOMElement類的Extend(擴展),然後把擴展類的實例加入到一個HTML文檔樹中: <?php class HTMLElement extends DOMElement { private $htmlDoc; protected $readonlyProperties = array(); function __construct() { call_user_func_array("parent::__construct", func_get_args()); $this->htmlDoc = new DOMDocument(); $this->htmlDoc->appendChild($this); } function __get($property) { return $this->getAttribute($property); } function __set($property, $value) { if (!in_array($property, $this->readonlyProperties)) { $this->setAttribute($property, $value); } } public function appendTo(DOMDocument $htmlDoc) { $node = $htmlDoc->importNode($this, true); $htmlDoc->appendChild($node); } public function getHTML() { return $this->htmlDoc->saveHTML(); } }
class Button extends HTMLElement { protected $readonlyProperties = array("type"); function __construct() { parent::__construct("input"); $this->setAttribute("type", "button"); } function __set($property, $value) { parent::__set($property, $value); } }
$html = new DOMDocument("1.0", "iso-8859-1"); $html->formatOutput = true; $btn = new Button(); $btn->value = "dd"; $btn->appendTo($html); echo $html->saveHTML(); ?>
|