簡體   English   中英

PHP DOMDocument在克隆/返回時更改節點類實例嗎?

[英]PHP DOMDocument change node class instances while cloning/return?

我設法使用PHP DOM實現來創建包含DOMElement子類的自定義文檔樹,但發現了一些非常奇怪的東西:克隆或返回DOMDocument似乎會更改子節點類。

基本例子

class Section extends DOMElement
{
  public function __construct($name, $value = null, $uri = null)
  {
    parent::__construct($name, $value, $uri);
  }
}

class Paragraph extends DOMElement
{
  public function __construct($name, $value = null, $uri = null)
  {
    parent::__construct($name, $value, $uri);
  }
}

function display_doc($label, DOMDocument $doc)
{
  $endl = (PHP_SAPI == "cli") ? "\n" : "<br />";
  $pad  = (PHP_SAPI == "cli") ? "\t" : "  ";
  echo ($label . $endl);

  $root = $doc->documentElement;
  echo ($pad . "root " . get_class($root) . $endl);
  echo ($pad . "first child " . get_class($root->firstChild) . $endl);
}

function test_dom($name, DOMDocument &$instance = null)
{
  $doc = ($instance) ? $instance : new DOMDocument("1.0", "utf-8");
  $root = $doc->appendChild($doc->createElement("root"));
  $section = new Section("section");

  $root->appendChild($section);
  $paragraph = new Paragraph("para");
  $section->appendChild($paragraph);

  $clone = clone $doc;

  display_doc($name . " - Inside function", $doc);
  display_doc($name . " - Inside function (clone)", $clone);

  return $doc;
}

$doc = test_dom("Using new instance");
display_doc("Returned doc in global scope", $doc);

$doc2 = new DOMDocument("1.0", "utf-8");
test_dom("Using global scope instance", $doc2);
display_doc("Modified doc in global scope", $doc2);

將輸出

Using new instance - Inside function
    root DOMElement
    first child Section
Using new instance - Inside function (clone)
    root DOMElement
    first child DOMElement
Returned doc in global scope
    root DOMElement
    first child DOMElement
Using global scope instance - Inside function
    root DOMElement
    first child Section
Using global scope instance - Inside function (clone)
    root DOMElement
    first child DOMElement
Modified doc in global scope
    root DOMElement
    first child DOMElement

克隆或返回文檔時(甚至通過引用), Section一個孩子的類從Section更改為簡單的DOMElement

  • 我的PHP版本是5.3.10,但在5.4下會發生相同的行為
  • 使用DOMDocument :: registerNodeClass將通過注冊的節點類轉換DOMElement ,但是我有多個DOMElement子類

我的問題不是真的要找到解決方法或其他解決方案,而是要了解這里發生了什么以及子節點是通過哪種機制轉換的。

編輯:我發現了一個與此問題相關的錯誤報告(已有2年的歷史): http : //www.mail-archive.com/php-bugs@lists.php.net/msg134710.html 擬議的解決方法工作正常,但尚不清楚它是真正的錯誤還是對DOM API的無效使用

當您使用new Paragraphnew Section您將需要將它們存儲在單獨的數組中以將其保留在內存中,以便DOMDocument不僅使用它的默認類。

錯誤報告是准確的,我認為PHP中DOM的整個實現都是有缺陷的。

將對象的副本保存在其他位置會占用大量內存,就像使用DOM一樣。 由於許多缺陷,我個人都在努力爭取一個體面的實施方案,所以您不是唯一的一個:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM