标题有点令人困惑,但我希望我能够解释我的挑战。我正在扩展 PHP DOMDocument 类,如下所示:<?phpuse DOMXPath;use DOMDocument;class BookXML extends \DOMDocument{ public function filterByYear(int $year) { $books = []; $document = new self(); $xpath = new DOMXPath($document); $booksObjs = $document->documentElement; $query = 'string(year)'; foreach ($booksObjs->childNodes as $booksObj) { $yearxml = $xpath->evaluate($query, $booksObj); if ($yearxml == $year) { $books[] = $booksObj; } } return $books; }}$xml = new BookXML();$xml->loadXML($content);$filteredXML = $xml->filterByYear(2015);该loadXML方法属于父类 (DOMDocument),但我需要它在子类中处于实例化状态,以便我可以访问加载的文档,并且我不应该向该方法传递任何更多参数filterByYear。我尝试过new self(),但它只创建了当前类的一个全新实例。我需要实例化对象,以便可以访问在类外部加载的 xml 内容。我是面向对象编程的新手,所以我希望我的解释有意义。
1 回答
DIEA
TA贡献1820条经验 获得超2个赞
正如您已经说过的,new self()将实例化一个新的。用于$this将其引用到对象本身:
class BookXML extends \DOMDocument
{
public function filterByYear(int $year)
{
$books = [];
$document = $this; // $this not new self()
$xpath = new DOMXPath($document);
$booksObjs = $document->documentElement;
$query = 'string(year)';
foreach ($booksObjs->childNodes as $booksObj) {
$yearxml = $xpath->evaluate($query, $booksObj);
if ($yearxml == $year) {
$books[] = $booksObj;
}
}
return $books;
}
}
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报
0/150
提交
取消