2
votes

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

4
You mix $dom with $this and don't call parent::__construct() if not inside the class self __construct() method, that makes no sense. joakimdahlstrom has the code. - hakre
Ah and the answer to your question is: No. - hakre
Yeah, I got it, I got it, how do I show the question has been answered. - CMS scripting

4 Answers

3
votes

__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.

2
votes

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

    }

}
1
votes

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

1
votes

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.