看这个例子:
这个类扩展了 DOMElement。每个 DOMElement 都必须是任何 DOMDocuement 的一部分才能进行修改。
class Xmlrize extends DOMElement
{
private static $dom;
public function __construct(/*. string .*/ $name,$value =null) {
parent::__construct($name,$value,null);
if(!self::$dom) {
self::$dom = new DOMDocument('1.0','UTF-8');
}
self::$dom->appendChild($this);
}
}
用于将数组添加到 DOM 中。如果数组的值不是 Xmlrize,那么我忽略它。
class Attributes extends Xmlrize {
public function __construct(array $attributes)
{
parent::__construct('Attributes');
foreach($attributes as $name => $value) {
$element = new Xmlrize($name);
if($value instanceof Xmlrize)
$element->appendChild($value);
$this->appendChild($element);
}
}
}
您可以在构造函数中添加属性实例
class Html extends Xmlrize {
public function __construct(Attributes $obj) {
parent::__construct('html');
$this->addAttributes($obj);
}
此方法显示属性是否是 Xmlrize 的实例。
protected function addAttributes(Attributes $attributes)
{
foreach($attributes->childNodes as $attribut) {
if($attribut->childNodes->length == 1) {
$item = $attribut->childNodes->item(0);
echo $attribut->nodeName.': ';
echo $item->nodeName.' has value '.$item->nodeValue.'. ';
echo 'Is it DomElement? ';
echo ($item instanceof DomElement) ? 'true' : 'false';
echo '. Is it Xmlrize? ';
echo ($item instanceof Xmlrize) ? 'true' : 'false';
echo '.'.PHP_EOL;
}
}
return null;
}
}
通过数组启动属性的示例。看看差异!
/* works as expected */
$like = new Html(new Attributes(
$xx = array('XXX'=> new Xmlrize('foo', 'baar'))
));
/* do not work as exptected */
$like = new Html(new Attributes(
array('XXX'=> new Xmlrize('foo', 'baar'))
));
?>
上面的示例返回:
XXX: foo has value baar. Is it DomElement? true. Is it Xmlrize? true.
XXX: foo has value baar. Is it DomElement? true. Is it Xmlrize? false.
为什么如果我添加 '$xx =' 该元素被视为 Xmlrize,如果不是,则不是?