PHP5 : Applying a method from an extended class on an object from the original (parent) class.
- by Glauber Rocha
Hello,
I'm trying to extend two native PHP5 classes (DOMDocument and DOMNode) to implement 2 methods (selectNodes and selectSingleNode) in order to make XPath queries easier. I thought it would be rather straighforward, but I'm stuck in a problem which I think is an OOP beginner's issue.
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);
}
}
Then I tried to do extend DOMNode to implement the same methods so I can perform an XPath query directly on a node:
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);
}
}
Now if I execute the following code (on an arbitrary XMLDocument):
$xmlDoc = new nDOMDocument;
$xmlDoc->loadXML(...some XML...);
$node1 = $xmlDoc->selectSingleNode("//item[@id=2]");
$node2 = $node1->selectSingleNode("firstname");
The third line works and returns a DOMNode object $node1. However, the fourth line doesn't work because the selectSingleNode method belongs to the nDOMNode class, not DOMNode.
So my question: is there a way at some point to "transform" the returned DOMNode object into a nDOMNode object? I feel I'm missing some essential point here and I'd greatly appreciate your help.
(Sorry, this is a restatement of my question http://stackoverflow.com/questions/2573820/)