Overriding in PHP

Overriding in PHP: In the context of object oriented programming method overriding means to replace parent method in child class.In overriding we can re-declare parent class method in child class. So, basically the purpose of overriding is to change the behavior of your parent class method.

When your class has some method and another class(derived class) want the same method with different behavior then using overriding you can completely change the behavior of base class(or parent class). The two methods with the same name and same parameter is called overriding.

Overriding context is not so difficult in PHP. As we all know overriding in PHP is a method of updating the inherited method from parent class to child class. So, in this case you will require method with same name in parent class as well as in child class and then we will see how the behavior of parent class method is changed when child class override the method of parent class.

In OOP PHP if we were to create a method in the child class having the same name, same number of parameters and the same access specifier as in it’s parent then we can say that we are doing method overriding. for example:

class ParentClass {
    public function test($param) {
        return \"\\n Parent - the parameter value is $param\";
    }
}
class ChildClass extends ParentClass {
    public function test($param) {
        echo \"\\n Child - the parameter value is $param\";
    }
}
$objParentClass = new ParentClass;
$objChildClass = new ChildClass;
$objParentClass->test(\'class ParentClass\');
$objChildClass->test(\'class ChildClass\');

The definition of polymorphism says that “if the decision to invoke a method is made by inspecting the object at run time then it is a case of polymorphism”. We can apply this rule in our example. Whether to call method test() of class ParentClass or class ChildClass is decided by inspecting the concerned object which is making the call to the method. Thus the method call will be based on the object.

Scroll to Top