不同类的PHP DOMDocument对象
我试图返回DOMDocument的根元素(不同类的PHP DOMDocument对象,php,xml,domdocument,Php,Xml,Domdocument,我试图返回DOMDocument的根元素($doc->documentElement),然后访问所有者文档的公共成员$foo。 这给了我 Undefined property: DOMDocument::$foo in /var/www/temp/test.php on line 16 因为在返回根元素之后,成员ownerDocument不再属于类\test\DOMDocument,而是属于\DOMDocument 代码怎么了 (PHP 5.5.9-1ubuntu4.5123) documen
$doc->documentElement
),然后访问所有者文档的公共成员$foo
。
这给了我
Undefined property: DOMDocument::$foo in /var/www/temp/test.php on line 16
因为在返回根元素之后,成员ownerDocument
不再属于类\test\DOMDocument
,而是属于\DOMDocument
代码怎么了
(PHP 5.5.9-1ubuntu4.5123)
documentElement->ownerDocument->foo;//酒吧
返回$doc->documentElement;
}
$doc=test();
echo$doc->ownerDocument->foo;//错误:$foo未定义
?>
ThW提出的解决方案
ownerDocument->foo;//酒吧
?>
这是ext/domgc中的一个bug。您始终需要对文档对象的有效引用。如果没有,对象可以将其类更改为\DOMDocument
,或者从内存中完全删除
在函数内创建文档,并仅返回文档元素节点,而不返回文档。$doc上的引用计数器在函数调用结束时变为零
如果将文档的创建和使用分开,这不会对您造成太大影响。在这种情况下,您将有一个带有文档对象的变量
<?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
?>
<?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
?>