0

is it possible to call parent class method x or constructor, automatically when child class any method like a,b,c .. is called?

abstract class parentCl {

    public function parentMethod()
    {
        echo "parent call";
    }
}

class childCl extends parentCl {

    public function __construct() {
        echo "construct";
    }

    public function childMethod($params)
    {
        echo "child call";
    }

    public function childMethod2($params)
    {
        echo "child call2";
    }


}


//like this case, 
$n = new childCl();
$n->childMethod(123);
$n->childMethod2(1234);

I want parentMethod() to be called

  • 2
    Then call it. `$this->parentMethod();` in any of your child methods – Machavity Jan 09 '17 at 13:36
  • Just in case the dupe isn't clear, the answer to the "automatic call" portion of your question is NO – Machavity Jan 09 '17 at 13:54
  • A bit hacky and dirty, but you could protect your public methods, and use the magic `__call()` method: [demo](https://3v4l.org/aEc2O) - but better if you do it explicitly via a `parent::parentMethod()` call to avoid the voodoo – Mark Baker Jan 09 '17 at 14:07

0 Answers0