2

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

alex
  • 479,566
  • 201
  • 878
  • 984
CMS scripting
  • 669
  • 1
  • 7
  • 13
  • 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](http://stackoverflow.com/questions/6300917/inheritance-problem-calling-parent-construct-function-in-subclass/6300982#6300982). – hakre Jun 10 '11 at 01:14
  • Ah and the answer to your question is: No. – hakre Jun 10 '11 at 01:16
  • Yeah, I got it, I got it, how do I show the question has been answered. – CMS scripting Jun 10 '11 at 01:40

4 Answers4

3

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

alex
  • 479,566
  • 201
  • 878
  • 984
2

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

    }

}
joakimdahlstrom
  • 1,575
  • 1
  • 11
  • 23
  • Oh ok, I got it, there is not even need to instantiate the class, I don't know why I was confused about this. Thank you my brother. – CMS scripting Jun 10 '11 at 01:15
1

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

zerkms
  • 249,484
  • 69
  • 436
  • 539
1

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.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390