Today's Question:  What does your personal desk look like?        GIVE A SHOUT

PHP function overloading puzzle clearer

  Pi Ke        2011-07-11 03:24:30       3,780        0    

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 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.