DOMDocument::registerNodeClass
(PHP 5 >= 5.2.0, PHP 7)
DOMDocument :: registerNodeClass - 用于创建基节点类型的注册扩展类
描述
public bool DOMDocument::registerNodeClass ( string $baseclass , string $extendedclass )
此方法允许您注册您自己的扩展DOM类,以供PHP DOM扩展之后使用。
这种方法不是DOM标准的一部分。
参数
baseclass
您想要扩展的DOM类。你可以在章节介绍中找到这些类的列表。
extendedclass
您的扩展课程名称。如果NULL
提供,任何以前注册的课程baseclass
将被删除。
返回值
成功时返回TRUE
或失败时返回FALSE
。
更新日志
版 | 描述 |
---|---|
5.2.2 | 在5.2.2之前,先注册的扩展类必须先注册,然后才能注册扩展相同基类的新类。 |
例子
示例#1向DOMElement添加一个新方法以简化我们的代码
<?php
class myElement extends DOMElement {
function appendElement($name) {
return $this->appendChild(new myElement($name));
}
}
class myDocument extends DOMDocument {
function setRoot($name) {
return $this->appendChild(new myElement($name));
}
}
$doc = new myDocument();
$doc->registerNodeClass('DOMElement', 'myElement');
// From now on, adding an element to another costs only one method call !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');
echo $doc->saveXML();
?>
上面的例子将输出:
<?xml version="1.0"?>
<root><child foo="bar"/></root>
示例#2将元素作为自定义类进行检索
<?php
class myElement extends DOMElement {
public function __toString() {
return $this->nodeValue;
}
}
$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");
$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));
// And take advantage of the __toString method..
echo $element;
?>
上面的例子将输出:
string(9) "myElement"
text in child
示例#3检索所有者文档
在实例化自定义DOMDocument时,ownerDocument属性将引用实例化的类,这意味着不需要(并且实际上不可能)使用DOMDocument :: registerNodeClass()和DOMDocument
<?php
class myDOMDocument extends DOMDocument {
}
class myOtherDOMDocument extends DOMDocument {
}
// Create myDOMDocument with some XML
$doc = new myDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$child = $doc->getElementsByTagName("child")->item(0);
// The current owner of the node is myDOMDocument
var_dump(get_class($child->ownerDocument));
// Import a node from myDOMDocument
$newdoc = new myOtherDOMDocument;
$child = $newdoc->importNode($child);
// The new owner of the node has changed to myOtherDOMDocument
var_dump(get_class($child->ownerDocument));
?>
上面的例子将输出:
string(13) "myDOMDocument"
string(18) "myOtherDOMDocument"
← DOMDocument::normalizeDocument
DOMDocument::relaxNGValidate →
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com