Monday, July 14, 2014

Function overriding in PHP with example

Definition
Rewrite the action of function in sub or derived class, which is already in base or super class.

Example
<?php
class Fruits
{
public function taste()
{
return 'Sweet';
}

public function color()
{
return 'Reddish orange';
}
}

class Greaps extends Fruits
{
public function color()  // Overriding color function.
{
return 'Black';
}
}

$greap=new Greaps();
echo 'Taste: '.$greap->taste().'<br />';
echo 'Color: '.$greap->color();
?>

Output:
Taste: Sweet
Color: Black

Notes:
We can avoid method overriding by declaring a function as final.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...