0

The title is a bit confusing but I hope I will be able to explain my challenge.

I am extending the PHP DOMDocument class like below:

<?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);


The loadXML method belongs to the parent class (DOMDocument), but I need it in its instantiated state in the child class so that I can access the loaded document, and I should not pass any more arguments to the filterByYear method. I tried new self() but it only creates a fresh new intsance of the current class. I need the instansiated object so that I can access the xml content that was loaded outside of the class. I am new to OOP so I hope my expalnation makes sense.

tendaitakas
  • 328
  • 5
  • 18

1 Answers1

1

As you've already stated, new self() will instantiate a new one. Use $this to reference it to the object itself:

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

Kevin
  • 41,694
  • 12
  • 53
  • 70