Overriding in PHP

In object-oriented programming overriding is to return the parent method in child class. You can re-declare the parent class method in the child class. Normally, the goal of overriding in PHP is to modify the response of the parent class method.

If your class has the unusual method and another derived class wants the same method with a distinctive response then using overriding you can totally modify the behavior of the base class or parent class as well. The two methods with the same name and the same parameter are called overriding.

How do overriding works?

Overriding is an idea where the derived class of the base class does the same task as the base class. The overriding can be on classes or methods. If the method is overriding then the name of the method the parameters, the access specifier is determined to be the same as that of the parent class method. There is no modification found in the implementation of the method in the subclass derived from the base class, at that time it is stated that the purpose of the subclass has overridden the way of the base class.

How to implement overriding in PHP?

The overriding idea is really light in PHP. As we all understand overriding in PHP is a method of refreshing the derived method from the parent class to the child class. So, in this example, you will need a method with the same name in the parent class as well as in the derived class and then we will see how the presence of the parent class method is modified when the derived class overrides the method of the parent class.

class BaseClass {
public function SOFT() {
echo "Base class <br />";
class DerivedClass extends BaseClass {
// override the method SOFT() of base class
public function SOFT() {
echo "Derived class";
$object = new BaseClass;
$object0 = new DerivedClass;
Base class
Derived class

In the above example, there are 2 classes, the derived class & the base class. The derived class increases the base class. Those classes are initiated and two objects $object and $object0 are performed. $object0 is an object of the derived class and $object is an object of a base class. These objects extra call the methods initialized in their particular classes.

Above you have observed that the base class and the derived class have the same method described SOFT(). When you perform this program, you will see that the SOFT() method has overridden the base class method SOFT().

Scroll to Top