Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force child classes to override a particular function in PHP

Tags:

oop

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.

like image 446
asim-ishaq Avatar asked May 30 '13 17:05

asim-ishaq


People also ask

Can you override a function in PHP?

Introduction to the PHP overriding methodTo override a method, you redefine that method in the child class with the same name, parameters, and return type. The method in the parent class is called overridden method, while the method in the child class is known as the overriding method.

What methods can be overridden in class PHP?

In function overriding, both parent and child classes should have same function name with and number of arguments. It is used to replace parent method in child class. The purpose of overriding is to change the behavior of parent class method. The two methods with the same name and same parameter is called overriding.

Can we override properties in PHP?

Is it possible to override parent class property from child class? Yes.

How the child class can access the properties of parent class explain with PHP example?

Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.


1 Answers

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

like image 186
gzm0 Avatar answered Oct 05 '22 03:10

gzm0