Расширенный объект DOMElement теряет свои свойства при импорте в другой документ - PullRequest
0 голосов
/ 29 марта 2011

При импорте расширенного объекта 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


?>

1 Ответ

0 голосов
/ 29 марта 2011

Возможно, есть лучшее решение, но вам может понадобиться 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!"
}

Демо здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...