扩展DOMDocument和DOMNode:返回对象的问题 [英] Extending DOMDocument and DOMNode: problem with return object
问题描述
我正在尝试扩展DOMDocument类,以便使XPath选择更容易。我写了这段代码:
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);
}
}
这些方法分别返回一个DOMNodeList和一个DOMNode对象。
我现在想做的是对DOMNode对象实现类似的方法。但是显然,如果我编写一个扩展DOMNode的类(myDOMNode),我将无法在myDOMDocument返回的节点上使用这两个额外的方法,因为它们是DOMNode(而不是myDOMNode)对象。
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.
任何提示?非常感谢。
推荐答案
尝试使用封装而不是继承。也就是说,编写一个类可以扩展本机DOMNode类,而不是编写一个DOMNode类的实例,并且只提供你需要的方法。
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.
允许您编写一个有效将DOMNode转换成MyNode的构造函数:
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)
}
对于MyDocument类,输出MyNode对象而不是DOMNode对象:
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));
}
}
这篇关于扩展DOMDocument和DOMNode:返回对象的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!