开发者

Extending DOMDocument and DOMNode: problem with return object

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:

class MyNode {
   function __construct($node) {
      $this->node = $node;
   }

   // (other helpful methods)

}

For your class MyDocument, you output MyNode objects rather than DOMNode objects:

class MyDocument {

   // (other helpful methods)

   function selectSingleNode($xpath) {

      return new MyNode($this->selectNodes($xpath)->item(0));
   }
}


Use registerNodeClass which will make the document always return nodes as your class instead of the default DOMElement

http://php.net/manual/en/domdocument.registernodeclass.php


Not sure I understand what are you doing. Probably you should create some class myDOMXPath extends DOMXPath which will return objects of my* classes and use it where it needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜