PHPverse 2025

Voting

The Note You're Voting On

ryoroxdahouse at hotmail dot com
17 years ago
I use DOM to generate dynamically XHTML document.

When trying to extend the DOMDocument and DOMElement classes, I found a very annoying bug concerning DOMDocument::$documentElement.

If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement.

In my situation, I cannot use DOMDocument::registerNodeClass() because the document element is not necessarily the base class for all the elements in my document.

*******
problem
*******

See bellow for the repro step:

<?php
class MyElement extends DOMElement{
public
$myProp="myProp";
public function
myMethod(){
return
'myMethod()';
}
}

$myDocument=new DOMDocument();
$myDocument->appendChild(new MyElement('myElement','myElement'));
echo (
'$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
echo (
'$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

Notice: Undefined property: DOMElement::$myProp in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 11
$myElement->myProp :

Fatal error: Call to undefined method DOMElement::myMethod() in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 12

*******
solution
*******

After searching around, I found a pretty odd way to fix this problem. It seems that you have to stock a reference to your appended document element in an user-defined (and persistent) variable (in other words, not only in DOMDocument::$documentElement). See below:

<?php
class MyElement extends DOMElement{
public
$myProp="myProp";
public function
myMethod(){
return
'myMethod()';
}
}

$myDocument=new DOMDocument();
$mydocumentElement=$myDocument->appendChild(new MyElement('myElement','myElement')); //here is the hack
echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
echo (
'$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

$myElement->myProp :myProp
$myElement->myMethod :myMethod()

Hope it will help.

<< Back to user notes page

To Top