PHP DOMDocument突然成为不同类的对象


PHP DOMDocument suddenly object of different class

>我正在尝试返回 DOMDocument 的根元素 ( $doc->documentElement (,然后访问ownerDocument的公共成员$foo。这给了我

Undefined property: DOMDocument::$foo in /var/www/temp/test.php on line 16

因为在返回根元素后,成员ownerDocument不再是类'test'DOMDocument而是'DOMDocument

代码有什么问题?

(PHP 5.5.9-1ubuntu4.5123)

<?php
namespace test;
class DOMDocument extends 'DOMDocument {
    public $foo = 'bar';
}
function test() {
    $doc = new DOMDocument();
    $doc->loadXML('<root></root>');
    echo $doc->documentElement->ownerDocument->foo; // bar
    return $doc->documentElement;
}
$doc = test();
echo $doc->ownerDocument->foo; // error: $foo is not defined
?>

ThW提出的解决方案

<?php
namespace test;
class DOMDocument extends 'DOMDocument {
    public $foo = 'bar';
}
function test($doc) {
    echo $doc->documentElement->ownerDocument->foo; // bar
    return $doc->documentElement;
}
$doc = new DOMDocument();
$doc->loadXML('<root></root>');
$doc2 = test($doc);
echo $doc2->ownerDocument->foo; // bar
?>

这是 ext/dom GC 中的一个错误。始终需要对文档对象的有效引用。如果不是,对象可以将其类更改为'DOMDocument或从内存中完全删除。

在函数中创建文档,并仅返回文档元素节点,而不返回文档。$doc上的引用计数器在函数调用结束时变为零。

如果您将文档的创建和使用分开,这不会对您产生太大影响。在这种情况下,您将有一个带有文档对象的变量。