An extended DOMElement object loses properties when imported into another document

When you transfer an extended DOMElement object with special properties to a different DOMDocument than the one that was created with all the properties, it is lost (I think that it actually does not copy no, but a new node is created for another document and only the values โ€‹โ€‹of the DOMElement class are copied to the new node ) What would be the best way to have the properties still available in the imported item?

Here is an example of a problem:

<?php class DOMExtendedElement extends DOMElement { private $itsVerySpecialProperty; public function setVerySpecialProperty($property) {$this->itsVerySpecialProperty = $property;} } // First document $firstDocument = new DOMDocument(); $firstDocument->registerNodeClass("DOMElement", "DOMExtendedElement"); $elm = $firstDocument->createElement("elm"); $elm->setVerySpecialProperty("Hello World!"); var_dump($elm); // Second document $secondDocument = new DOMDocument(); var_dump($secondDocument->importNode($elm, true)); // The imported element is a DOMElement and doesn't have any other properties at all // Third document $thirdDocument = new DOMDocument(); $thirdDocument->registerNodeClass("DOMElement", "DOMExtendedElement"); var_dump($thirdDocument->importNode($elm, true)); // The imported element is a DOMExtendedElement and does have the extra property but it empty ?> 
0
source share
1 answer

It may have a better solution, but you may need to clone first object

 class DOMExtendedElement extends DOMElement { private $itsVerySpecialProperty; public function setVerySpecialProperty($property) {$this->itsVerySpecialProperty = $property;} public function getVerySpecialProperty(){ return isset($this->itsVerySpecialProperty) ?: ''; } } // First document $firstDocument = new DOMDocument(); $firstDocument->registerNodeClass("DOMElement", "DOMExtendedElement"); $elm = $firstDocument->createElement("elm"); $elm->setVerySpecialProperty("Hello World!"); var_dump($elm); $elm2 = clone $elm; // Third document $thirdDocument = new DOMDocument(); $thirdDocument->registerNodeClass("DOMElement", "DOMExtendedElement"); $thirdDocument->importNode($elm2); var_dump($elm2); 

Result:

 object(DOMExtendedElement)#2 (1) { ["itsVerySpecialProperty:private"]=> string(12) "Hello World!" } object(DOMExtendedElement)#3 (1) { ["itsVerySpecialProperty:private"]=> string(12) "Hello World!" } 

Demo here

0
source

All Articles