导入到另一个文档时,扩展的DOMElement对象会丢失它的属性 [英] Extended DOMElement object loses it's properties when imported into another document

查看:116
本文介绍了导入到另一个文档时,扩展的DOMElement对象会丢失它的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将具有特定属性的扩展DOMElement对象导入到另一个DOMDocument中,而不是使用所有属性创建的对象都丢失(我猜想它实际上不会复制no,而是为其他文档创建一个新节点, DOMElement类的值将复制到新节点)。在导入元素中仍然可以使用属性的最佳方式是什么?

When importing an extended DOMElement object with specific properties into another DOMDocument than the one it was created with all properties are lost (I guess it doesn't actually copy the no but a new node is created for the other document and just the values for the DOMElement class are copied to the new node). What would be the best way to have the properties still available in the imported element?

以下是问题的一个示例:

Here's an example of the problem:

<?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


?>


推荐答案

它可能有更好的解决方案,但您可能需要克隆第一个对象

It may have a better solution but you may need to clone the first object

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

演示这里

这篇关于导入到另一个文档时,扩展的DOMElement对象会丢失它的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆