【问题标题】:PHP accessing values from the parent class [duplicate]PHP从父类访问值[重复]
【发布时间】:2020-11-02 04:11:15
【问题描述】:

标题有点混乱,但我希望我能解释我的挑战。

我正在扩展 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),但我需要它在子类中的实例化状态,以便我可以访问加载的文档,并且我不应该再向 @987654323 传递任何参数@ 方法。我尝试了new self(),但它只会创建当前类的全新实例。我需要实例化对象,以便可以访问在类外部加载的 xml 内容。我是 OOP 的新手,所以我希望我的解释是有道理的。

【问题讨论】:

    标签: php xml oop inheritance dom


    【解决方案1】:

    正如您已经说过的,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;
        }
    }
    

    Sample Output

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 2019-07-04
      • 2013-11-14
      • 2021-11-16
      • 2018-06-16
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      相关资源
      最近更新 更多