Thursday, February 2, 2012

Overloading and Overriding in PHP with Examples



Overloading
Overriding





Function
Possible
Not possible





Method
Possible
Possible









function overriding:


Function overriding is not possible.  In PHP, we try to use two difference function in same name in same file or different included file.  PHP will throw an error like "Fatal error: Cannot redeclare compute() (previously declared".  So, Function overriding is not possible in PHP 5.  It may possible in upcoming version of PHP.  I am waiting for that.. :)


method overriding:


An example of overriding:

class Foo {
   function myFoo() {
      return "Foo";
   }
}
class Bar extends Foo {
   function myFoo() {
      return "Bar";
   }
}

$foo = new Foo;
$bar = new Bar;
echo($foo->myFoo()); //"Foo"
echo($bar->myFoo()); //"Bar"
 
Note: Bar class overriding the myFoo() function from the Foo class and calling
its own method myFoo(); 



Function overloading:

function compute($first, $second, $third = 0) {
      return $first+$second+$third;
   }


echo "<br>Example #1: ".compute(10, 20);
echo "<br>Example #2: ".compute(10, 20, 30);

Output:
Example #1: 30
Example #2: 60

Example for Class Overloading :

class Addition {
    function compute($first, $second, $third = 0) {
      return $first+$second+$third;
   }
}

$AdditionObj = new Addition;
echo "<br>Example #3: ".$AdditionObj->compute(100, 200);
echo "<br>Example #4: ".$AdditionObj->compute(100, 200, 30);

Output:
Example #3: 300
Example #4: 330

No comments:

Post a Comment

Followers