PHP function overloading puzzle clearer

Summary

PHP's definition of "overloading" involves dynamically adding object properties and methods at runtime, primarily through magic methods such as __get, __set, and __call. These magic methods allow classes to intercept and process calls to undefined members, providing flexible object extension. To achieve traditional function overloading, similar to Java, developers can omit explicit arguments and inspect runtime parameters using func_num_args and func_get_args. PHP's weak typing and the use of default argument values also offer convenient ways to handle functions with varying argument counts or types.

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.

Some 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
= function_get_args();
    swtich
(count($args)) {
       
case 1:
           
// one argument passed
           
break;
       
case 2:
           
// two arguments passed
           
break;
       
default:
           
// illegal numer of arguments
           
break;
   
}
}

Actually in PHP,because of the weak data type,it is very convenient for
the function overloading,what we need to do is to check the data type
in the function to realized function overloading. Also by setting the
default value,we can also solve the function overloading with various
number of arguments problem.

Note: Some of the materials in this article are extracted from
http://stackoverflow.com/questions/1512295/what-is-php-function-overloading-for


PHP OOP FUNCTION OVERLOADING DEFAULT VAL

  RELATED

  COMMENTS

0

No comment for this article.