Hello Readers
overloading and overridding in php
In php overloading define functions have similar signatures but thy have different parameters.
Overriding means one class may have override the another methods where the parent class defined a method and derived class override that method.
3. An example of overriding is given below:
<?php
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"
?>
Another example overriding:
class parentclass {
function name() {
return 'Parent';
}
}
class childclass extends parentclass {
function name() {
return 'Child';
}
}
$obj = new childclass();
echo $obj->name();
4. Overloading declare a functions multiple times with different number of parameters.
An example of Overloading is given below:
<?php
function foo($a) {
return $a;
}
function foo($a, $b) {
return $a + $b;
}
echo foo(5);
echo foo(5, 2);
?>
<b>output:</b>
"5"
"7"
5. If we say in real world overloading means assigning some extra stuff to someone, so same as in php calling extra functions.
- overloading appear in the same class or a subclass.
7. overloading have the same but they have different parameter lists and can have different return types.
8. overriding methods appears in subclass.
9. overriding have the access specifier for the overriding method.
10. If the superclass method is public, the overriding method must be public.
- If the superclass method is package, the overriding method may be package, protected, or public.
0 Comment(s)