问题
When importing an extended DOMElement object with specific properties into another DOMDocument than the one it was created with all properties are lost (I guess it doesn't actually copy the no but a new node is created for the other document and just the values for the DOMElement class are copied to the new node). What would be the best way to have the properties still available in the imported element?
Here's an example of the 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's empty
?>
回答1:
It may have a better solution but you may need to clone
the 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
来源:https://stackoverflow.com/questions/5473967/extended-domelement-object-loses-its-properties-when-imported-into-another-docu