標題有點令人困惑,但我希望我能夠解釋我的挑戰。我正在擴展 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 關注
- 157 瀏覽
添加回答
舉報
0/150
提交
取消