Php 扩展DOMDocument和DOMNode:返回对象存在问题
我正在尝试扩展DOMDocument类,以便更容易地选择XPath。我写了这段代码:Php 扩展DOMDocument和DOMNode:返回对象存在问题,php,oop,dom,domdocument,Php,Oop,Dom,Domdocument,我正在尝试扩展DOMDocument类,以便更容易地选择XPath。我写了这段代码: class myDOMDocument extends DOMDocument { function selectNodes($xpath){ $oxpath = new DOMXPath($this); return $oxpath->query($xpath); } function selectSingleNode($xpath){ return $this->
class myDOMDocument extends DOMDocument {
function selectNodes($xpath){
$oxpath = new DOMXPath($this);
return $oxpath->query($xpath);
}
function selectSingleNode($xpath){
return $this->selectNodes($xpath)->item(0);
}
}
这些方法分别返回一个DOMNodeList和一个DOMNode对象。
我现在要做的是实现与DOMNode对象类似的方法。但很明显,如果我编写一个扩展DOMNode的类(myDOMNode),我将无法在myDOMDocument返回的节点上使用这两个额外的方法,因为它们是DOMNode(而不是myDOMNode)对象
我是一个对象编程的初学者,我尝试过各种各样的想法,但它们都会走向死胡同
有什么提示吗?事先非常感谢。我不知道你在干什么。可能您应该创建一些类myDOMXPath扩展了DOMXPath,它将返回my*类的对象,并在需要时使用它。尝试使用封装而不是继承。也就是说,与其编写扩展本机DOMNode类的类,不如编写一个类在其中存储DOMNode的实例,并且只提供所需的方法 这允许您编写一个构造函数,有效地将DOMNode转换为MyNode:
class MyNode {
function __construct($node) {
$this->node = $node;
}
// (other helpful methods)
}
对于类MyDocument,可以输出MyNode对象而不是DOMNode对象:
class MyDocument {
// (other helpful methods)
function selectSingleNode($xpath) {
return new MyNode($this->selectNodes($xpath)->item(0));
}
}
使用registerNodeClass,这将使文档始终将节点作为类而不是默认的DomeElement返回