In languages like Java, overloading can be used in this way:
void test($foo, $bar){}
int test($foo){}
Then if you called test()
with 2 arguments e.g test($x, $y);
, the first function would be called. If you passed only 1 argument e.g test($x);
, the 2nd function would be called.
From the manual it seems that php 5 does have overloading, but what is it for? I can't seem to understand the manual on this topic..
PHP's meaning of overloading is different than Java's. In PHP, overloading means that you are able to add object members at runtime, by implementing some of the __magic
methods, like __get
, __set
, __call
, __callStatic
. You load objects with new members.
Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.
An example:
class Foo
{
public function __call($method, $args)
{
echo "Called method $method";
}
}
$foo = new Foo;
$foo->bar(); // Called method bar
$foo->baz(); // Called method baz
And by the way, PHP supports this kind of overloading since PHP 4.3.0. The only difference is that in versions prior to PHP 5 you had to explicitly activate overloading using the overload()
function.
If you want to overload a function like in Java, don’t specify any arguments and use the func_num_args
and func_get_args
function to get the number of arguments or the arguments themselves that were passed to that function:
function test() {
$args = func_get_args();
switch (count($args)) {
case 1:
// one argument passed
break;
case 2:
// two arguments passed
break;
default:
// illegal numer of arguments
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With