I’m trying to extend the DOMDocument class so as to make XPath selections easier. I wrote this piece of code:
class myDOMDocument extends DOMDocument {
function selectNodes($xpath){
$oxpath = new DOMXPath($this);
return $oxpath->query($xpath);
}
function selectSingleNode($xpath){
return $this->selectNodes($xpath)->item(0);
}
}
These methods return a DOMNodeList and a DOMNode object, respectively.
What I’d like to do now is to implement similar methods to the DOMNode objects. But obviously if I write a class (myDOMNode) that extends DOMNode, I won’t be able to use these two extra methods on the nodes returned by myDOMDocument because they’re DOMNode (and not myDOMNode) objects.
I’m rather a beginner in object programming, I’ve tried various ideas but they all lead to a dead-end.
Any hints? Thanks a lot in advance.
Try using encapsulation instead of inheritance. That is, instead of writing a class that extends the native DOMNode class, write a class stores an instance of DOMNode inside it, and provides only the methods you need.
This allows you to write a constructor that effective turns a DOMNode into a MyNode:
For your class MyDocument, you output MyNode objects rather than DOMNode objects: