Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silently call parent method behind my back [duplicate]

Tags:

php

parent

Possible Duplicate:
Enforcing call to parent method

I have a class like this

abstract class theme{

  abstract function header(){
    // do stuff here
  }

  abstract function footer(){
    // do stuff here

  }

}

so all child classes must have these 2 methods:

class Atheme extends theme{

  function header(){
    // do stuff here

    echo ..
  }

  function footer(){
    // do stuff here

    echo ..
  }

}

Now when I call one of these methods:

$atheme = new Atheme;

$atheme->header();

I want the header() method from the child class to automatically call the parent class header() method, without specifically calling parent::header() in the child class.

Is this possible?

like image 578
Alex Avatar asked Oct 09 '22 17:10

Alex


1 Answers

If you have only one level of inheritance, you can accomplish this by doing something like:

abstract class theme {
    final public function header() {
        // do parent class stuff
        $this->_header();
    }

    abstract protected function _header();

    // ditto for footer
}

class Atheme extends theme {
    protected function _header() {
        // do child class stuff
    }
}

If the inheritance chain is arbitrarily long, then you'll need to use a callback chain.

like image 143
FtDRbwLXw6 Avatar answered Oct 12 '22 12:10

FtDRbwLXw6