Php – Force child classes to override a particular function in PHP

oopphp

I am creating a reporting library in PHP and developed an abstract class named ReportView. This will provide the basic functionality of a report like Generating header and footer, create parameter form.

There will be another function named generate_report in this class. Currently it is empty in abstract class as at this level we do not know the contents of report. Further it includes a render function which calls this generate_report function and sends output to browser.

So I need whenever a child class inherits from ReportView it must implement
the generate_report method otherwise PHP must give error. Is there any keyword or method through which we can enforce implemetation of a specific function.

Best Solution

Do the following:

abstract class ReportView {
  abstract protected function generate_report();

  // snip ...

}

class Report extends ReportView {
  protected function generate_report() { /* snip */ }
}

Any class that extends ReportView and is not abstract must implement generate_report (and any other abstract function in its super classes for that matter).