2011-03-29 3 views
0

특정 속성이있는 확장 DOMElement 객체를 모든 속성을 사용하여 만든 DOMDocument로 가져 오는 경우 실제로 손실되지 않습니다. 다른 문서에 대해 새 노드가 만들어지고 DOMElement 클래스의 값만 새 노드에 복사됩니다. 가져온 요소에서 속성을 계속 사용할 수있는 가장 좋은 방법은 무엇입니까?확장 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 


?> 
+0

결국 목표는 무엇입니까? XML 저장? – Shikiryu

답변

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을 여기

문제의 예

+0

예에서 마지막 행의 var_dump는 가져온 요소를 출력하지 않고 $ firstDocument의 복제 된 요소를 출력합니다. 다음과 같아야합니다. var_dump ($ thirdDocument-> importNode ($ elm, true)); 당신은 그 자산이 여전히 사라진 것을 보게 될 것입니다. – Paul

관련 문제