Reputation: 795
I have written below classes to make certain DOM operations easier. I want the Easy_Dom_Element's functions to be able to accept both a string and an element as input though. To do that I have to access DOMDocument's createElement method. The call to Easy_Dom::toElement works fine, but $this within that method points to the Easy_Dom_Element instead of Easy_Dom itself. I've tried a static call to createElement like so: Easy_Dom::createElement($element)
but for some reason that is not allowed.
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();
Upvotes: 0
Views: 355
Reputation: 795
Just when I was about to give up on this I finally figured it out, it turns out the answer was really simple.
Just reference the DOMElement's DOMDocument using the ownerDocument property like this:
$DOMDocumentFunctionResult = $this->ownerDocument->DOMDocumentFunction();
So in my example:
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;
}
}
Upvotes: 1
Reputation: 13
What version of PHP are you using?
< PHP 5.3 doesn't allow calling of static methods of inherited classes.
See : https://www.php.net/lsb
Upvotes: 0