我正在尝试扩展两个原生 PHP5 类(DOMDocument 和 DOMNode)来实现 2 个方法(selectNodes 和 selectSingleNode),以使 XPath 查询更容易。我认为这将是相当直截了当的,但我陷入了一个我认为是 OOP 初学者问题的问题。
class nDOMDocument extends DOMDocument {
public function selectNodes($xpath){
$oxpath = new DOMXPath($this);
return $oxpath->query($xpath);
}
public function selectSingleNode($xpath){
return $this->selectNodes($xpath)->item(0);
}
}
然后我尝试扩展 DOMNode 以实现相同的方法,这样我就可以直接在节点上执行 XPath 查询:
class nDOMNode extends DOMNode {
public function selectNodes($xpath){
$oxpath = new DOMXPath($this->ownerDocument,$this);
return $oxpath->query($xpath);
}
public function selectSingleNode($xpath){
return $this->selectNodes($xpath)->item(0);
}
}
现在,如果我执行以下代码(在任意 XMLDocument 上):
$xmlDoc = new nDOMDocument;
$xmlDoc->loadXML(...some XML...);
$node1 = $xmlDoc->selectSingleNode("//item[@id=2]");
$node2 = $node1->selectSingleNode("firstname");
第三行运行并返回一个 DOMNode 对象 $node1。但是,第四行不起作用,因为 selectSingleNode 方法属于 nDOMNode 类,而不是 DOMNode。所以我的问题是:有没有办法将返回的 DOMNode 对象“转换”为 nDOMNode 对象?我觉得我在这里遗漏了一些要点,非常感谢您的帮助。
(对不起,这是对我的问题Extending DOMDocument and DOMNode: problem with return object的重述)