Nic*_*uin 5 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->selectNodes($xpath)->item(0);
}
}
Run Code Online (Sandbox Code Playgroud)
这些方法分别返回DOMNodeList和DOMNode对象.我现在要做的是为DOMNode对象实现类似的方法.但显然如果我编写一个扩展DOMNode的类(myDOMNode),我将无法在myDOMDocument返回的节点上使用这两个额外的方法,因为它们是DOMNode(而不是myDOMNode)对象.
我是对象编程的初学者,我尝试了各种各样的想法,但它们都导致了死胡同.
任何提示?非常感谢提前.
尝试使用封装而不是继承。也就是说,不要编写一个扩展本机 DOMNode 类的类,而是编写一个在其中存储 DOMNode 实例的类,并仅提供您需要的方法。
这允许您编写一个构造函数,有效地将 DOMNode 转换为 MyNode:
class MyNode {
function __construct($node) {
$this->node = $node;
}
// (other helpful methods)
}
Run Code Online (Sandbox Code Playgroud)
对于类 MyDocument,您输出 MyNode 对象而不是 DOMNode 对象:
class MyDocument {
// (other helpful methods)
function selectSingleNode($xpath) {
return new MyNode($this->selectNodes($xpath)->item(0));
}
}
Run Code Online (Sandbox Code Playgroud)