Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell a PHP Class to always run it's constructor when it is extended

From what I understand, when a PHP Class is extended, it's constructor is not called? So in the below, the method Options_Page_Template->on_enqueue_scripts() is never actually run -

class Options_Page_Template{

    function __construct(){ 

        /** Enqueue scrips and styles for use in this plugin */
        add_action('wp_enqueue_scripts', array(&$this, 'on_enqueue_scripts'));

    }

    function on_enqueue_scripts(){

        { do Whatever here }

    }

}

class Options_Home extends Options_Page_Template{

    function __construct(){ 

        { Add various actions here }

    }


}

Is there a way of telling Options_Page_Template() to always run it's own __constructor() when it is extended? I know I can use parent::__construct(), but that involves adding the code to all the files that extend the Class.

I also tried the the old-school method of giving the constructor the same name as the Class, but PHP is obviously more clever than that, as it did not work. Thanks.

like image 434
David Gard Avatar asked Feb 17 '23 23:02

David Gard


1 Answers

There's no way. A good rule of thumb for all your code, is to always call parent::__construct for every subclass that overrides the constructor; and explicitly comment within the constructor if you are not, and why.

In general, for functions and con/destructors, if you override something; you are also responsible for calling the parent function.

like image 138
Evert Avatar answered Mar 05 '23 18:03

Evert