导入到另一个文档时,扩展的DOMElement对象会丢失它的属性

将具有特定属性的扩展DOMElement对象导入另一个DOMDocument而不是使用所有属性创建的那个DOMDocument时(我猜它实际上不会复制no,但是为另一个文档创建了一个新节点,而只是为其创建了值DOMElement类被复制到新节点)。在导入的元素中仍然可以使用属性的最佳方法是什么? 这是一个问题的例子:
<?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


?>
    
已邀请:
它可能有更好的解决方案,但您可能需要
clone
第一个对象
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!"
}
在这里演示     

要回复问题请先登录注册