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

时间:2011-03-29 14:15:03

标签: php dom domdocument extending

将具有特定属性的扩展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


?>

1 个答案:

答案 0 :(得分:0)

它可能有更好的解决方案,但您可能需要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!"
}

Demo here