0

特定のプロパティを持つ拡張された DOMElement オブジェクトを別の 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


?>
4

1 に答える 1

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!"
}

デモはこちら

于 2011-03-29T14:55:53.660 に答える