我编写了以下类来使某些DOM操作更容易。我希望Easy_Dom_Element的函数能够接受字符串和元素作为输入。为此,我必须访问DOMDocument的createElement方法。对Easy_Dom :: toElement的调用工作正常,但该方法中的$ this指向Easy_Dom_Element而不是Easy_Dom本身。我尝试过静态调用createElement,如下所示:Easy_Dom::createElement($element)
但由于某种原因不允许这样做。
class Easy_Dom extends DOMDocument{
/*function __construct(){
$this->registerNodeClass('DOMElement', 'Easy_Dom_Element');
}*/
//Gets the first element by tag name
function getElement($tagName){
return $this->getElementsByTagName($tagName)->item(0);
}
//Creates DOMElement from string if needed
function toElement($element){
if(is_string($element))$element = $this->createElement($element);
return $element;
}
}
class Easy_Dom_Element extends DOMElement{
function prependChildEl($element){
$element = Easy_Dom::toElement($element);
$this->insertBefore($element, $this->firstChild);
return $element;
}
function appendChildEl($element){
$element = Easy_Dom::toElement($element);
$this->appendChild($element);
return $element;
}
}
$_testxml = new Easy_Dom('1.0', 'ISO-8859-1');
$_testxml->registerNodeClass('DOMElement', 'Easy_Dom_Element');
//load defaults
$_testxml->load('default.xml');
//test above classes
$test = $_testxml->getElement('general_title');
$test->appendChildEl('test');
echo $test->nodeValue;
echo $_testxml->saveXML();
答案 0 :(得分:1)
就在我即将放弃这一点时,我终于明白了,事实证明答案非常简单。
只需使用ownerDocument属性引用DOMElement的DOMDocument,如下所示:
$DOMDocumentFunctionResult = $this->ownerDocument->DOMDocumentFunction();
所以在我的例子中:
class Easy_Dom extends DOMDocument{
/*function __construct(){
$this->registerNodeClass('DOMElement', 'Easy_Dom_Element');
}*/
//Gets the first element by tag name
function getElement($tagName){
return $this->getElementsByTagName($tagName)->item(0);
}
//Creates DOMElement from string if needed
function toElement($element){
if(is_string($element))$element = $this->createElement($element);
return $element;
}
}
class Easy_Dom_Element extends DOMElement{
function prependChildEl($element){
$element = $this->ownerDocument->toElement($element);
$this->insertBefore($element, $this->firstChild);
return $element;
}
function appendChildEl($element){
$element = $this->ownerDocument->toElement($element);
$this->appendChild($element);
return $element;
}
}
答案 1 :(得分:0)