Question

I have a class named Display which extends class Layout, which extends class DOMDocument. I get: Fatal error: Call to a member function loadHTMLFile() on a non-object. Code as follows:

In index.php :

 $dom = new Display();
 $dom->displayData();

In Display.php :

class Display extends Layout {

    public function displayData(){

    $dom = parent::__construct();
    $dom->loadHTMLfile("afile.html");
    echo $dom->saveHTML();

    }

}

My question is: When I call parent::__construct() , isn't this the same as using "new DOMDocument", since the Display class extends Layout and DOMDocument?Thanks

Was it helpful?

Solution

If you have the loadHTMLfile function in your parent class, the subclass will inherit it. So you should be able to do:

class Display extends Layout {

    public function displayData(){

        $this->loadHTMLfile("afile.html");
        echo $this->saveHTML();

    }

}

OTHER TIPS

__construct() is a magic method that is called when you instantiate the object.

Calling it is not the same as using the new operator.

In my experience, I have only ever used parent::__construct() inside of the __construct() of a subclass when I need the parent's constructor called.

It is not the same because constructor in php doesn't return anything

You typically call the parent's constructor inside the subclass's constructor. You're calling it in the displayData() method. It is only necessary to call the parent's constructor explicitly in the subclass constructor if you do additional work in the subclass constructor. Inheriting it directly without changes means you needn't call the parent constructor.

Calling the parent constructor will not return a value (object), as instantiating the object would.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top