PHP 从父类访问值

标题有点令人困惑,但我希望我能够解释我的挑战。


我正在扩展 PHP DOMDocument 类,如下所示:


<?php

use 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 内容。我是面向对象编程的新手,所以我希望我的解释有意义。


凤凰求蛊
浏览 92回答 1
1回答

DIEA

正如您已经说过的,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;    }}
打开App,查看更多内容
随时随地看视频慕课网APP