asim-ishaq
asim-ishaq

Reputation: 2230

Force child classes to override a particular function in PHP

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.

Upvotes: 10

Views: 12829

Answers (3)

Martin Bean
Martin Bean

Reputation: 39439

Sounds like you’d be better off creating an interface, which would enforce you to define those methods in classes that then implement this interface.

<?php
interface ReportInterface {
    public function generate();
}

class MyReportClass implements ReportInterface {
}

Instantiating MyReportClass here will throw a fatal error, telling you generate() has not been implemented.

Edit: You can also create abstract classes that implement this interface. You can have your abstract class contain any methods all extending classes need, and have your interface define any methods you need to be defined by extending classes.

Upvotes: 7

mpen
mpen

Reputation: 283335

You need to declare the method as abstract as well (and don't give it a method body), otherwise the derived classes will not be forced to implement it.

Alternatively, you could implement the method but have it just throw an Exception (not sure why you would want to do this).

Lastly, if all the methods in your base class are "abstract" (do not have bodies) then you can make the class into an Interface instead.

Upvotes: 1

gzm0
gzm0

Reputation: 14842

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).

Upvotes: 31

Related Questions