Search code examples
phpclassconstructorextend

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.


Solution

  • You must always use parent::__construct() if you are createing a __construct in both classes You do have an option to turn it around. You could have your parent class constructor check for the existence of a custom constructor in the child and run it.

    <?php
    class Options_Page_Template{
        function __construct(){ 
            if (method_exists($this,'__beforeconstruct'))
              $this->__beforeconstruct();
    
            echo "construct class<br/>";
    
            if (method_exists($this,'__afterconstruct'))
              $this->__afterconstruct();
    
        }
    
        function on_enqueue_scripts(){
        }
    }
    
    class Options_Home extends Options_Page_Template{
        function __beforeconstruct(){ 
           echo "Extended class before<br/>";
        }
    
        function __afterconstruct(){ 
           echo "Extended class after<br/>";
        }
    }
    
    new Options_Home();
    
    ?>
    

    output:

    Extended class before
    construct class
    Extended class after