Page Topic

You are currently viewing Method Overriding in PHP

Method Overriding in PHP

What is method overriding in PHP?

In object oriented programming overriding is to replace parent method in child class. In overriding you 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.


How to implement overriding in PHP?

Overriding concept is very easy 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.

Following is an example of overriding in PHP:
<?php

class parent_class
{
public function text()    //text() is a parent class method
{

echo “Hello!! everyone I am parent class text method”.”</br>”;
}
public function test()
{
echo “Hello!! I am second method of parent class”.”</br>”;
}
}

class child extends parent_class
{
public function text()     // Text() parent class method which is override by child class
{
echo “Hello!! Everyone i am child class”;
}
}

$obj= new parent_class();
$obj->text();            // display the parent class method echo

$obj= new parent_class();
$obj->test();

$obj= new child();
$obj->text();                 // display the child class method echo

?>

Output: 


Hello!! Everyone I am parent class text method

Hello!! I am second method of parent class

Hello!! everyone i am child class

Leave a Reply