Php 扩展的DomeElement对象将丢失它';导入到另一个文档中时的属性
当将具有特定属性的扩展DomeElement对象导入到另一个DOMDocument中时,所有属性都会丢失(我猜它实际上并没有复制no,而是为另一个文档创建了一个新节点,并且只将DomeElement类的值复制到新节点)。让属性在导入的元素中仍然可用的最佳方法是什么 下面是一个问题示例:Php 扩展的DomeElement对象将丢失它';导入到另一个文档中时的属性,php,dom,domdocument,extending,Php,Dom,Domdocument,Extending,当将具有特定属性的扩展DomeElement对象导入到另一个DOMDocument中时,所有属性都会丢失(我猜它实际上并没有复制no,而是为另一个文档创建了一个新节点,并且只将DomeElement类的值复制到新节点)。让属性在导入的元素中仍然可用的最佳方法是什么 下面是一个问题示例: <?php class DOMExtendedElement extends DOMElement { private $itsVerySpecialProperty; public
<?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
?>
它可能有更好的解决方案,但您可能需要克隆第一个对象
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);
结果:
object(DOMExtendedElement)#2 (1) {
["itsVerySpecialProperty:private"]=>
string(12) "Hello World!"
}
object(DOMExtendedElement)#3 (1) {
["itsVerySpecialProperty:private"]=>
string(12) "Hello World!"
}
在您的示例中,最后一行的var_dump实际上并没有输出导入的元素,而是$firstDocument的克隆元素。它应该是:var_dump($thirdDocument->importNode($elm,true));你终究会看到那处房产还是没了你的最终目标是什么?保存XML?