pTutorial

New way to learn PHP

PHP 5 Method overriding

Method overriding

Whenever a parent class and the child class are having same method and different functionality. This concept is known as method overriding.

Priority always goes to the local method. That means if you are creating an object of Computer class then always execute Computer class method, it cannot be parent class method if overriding is there.

Creation of overridden method

To override a method, create the parent class and the child class with the same method name. The following example shows the functionality of overridden

Example of class

<?php

class Computer 
{
public function display() 
{
echo "parent class or Computer class method";
}
}
class Laptop extends Computer {
public function display() 
{
echo "Child class or Laptop class method";
}
}

$uk = new Laptop();
$uk->display();	  
?>

Output

Child class or Laptop class method

In the above example, both classes Computer and Laptop are having same method. When we are creating child class object then child class display method get executed.

Note: Child class method is called when using an object of child class and parent class method is called when using an object of parent class and.

Example of PHP method overriding

<?php

class Computer 
{
public function comp() 
{
echo " 

This is a Computer...

"; } public function sound() { echo "

Connect sound to listen sound

"; } public function consume() { $this-> comp(); $this-> sound(); } } class Laptop extends Computer { public function comp() { echo "

This is a Laptop...

"; } public function sound() { echo "

There is no need to connect sound

"; } } echo " Computer class details"; $apple = new Computer; $apple-> consume(); echo " Laptop class details "; $Laptop = new Laptop; $Laptop-> consume(); ?>

Output

Computer class details
This is a Computer...
Connect sound to listen sound
Laptop class details
This is a Laptop...
There is no need to connect sound


QUOTES OF THE DAY

The basis of all progress is self-reliance

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER