简体   繁体   中英

Inheritance problem: calling parent construct function in subclass

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

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

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

    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM