What is PHP function overloading for?

前端 未结 3 1317
死守一世寂寞
死守一世寂寞 2020-12-24 03:08

In languages like Java, overloading can be used in this way:

void test($foo, $bar){}
int test($foo){}

Then if you called test()

相关标签:
3条回答
  • 2020-12-24 03:41

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-24 03:44

    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.

    0 讨论(0)
  • 2020-12-24 03:49

    To over load a function simply do pass parameter as null by default,

    class ParentClass
    {
       function mymethod($arg1 = null, $arg2 = null, $arg3 = null)  
       {  
         if( $arg1 == null && $arg2 == null && $arg3 == null ){ 
            return 'function has got zero parameters <br />';
         }
         else{
           $str = '';
           if( $arg1 != null ) 
            $str .= "arg1 = ".$arg1." <br />";
    
           if( $arg2 != null ) 
            $str .= "arg2 = ".$arg2." <br />";
    
           if( $arg3 != null ) 
            $str .= "arg3 = ".$arg3." <br />";
    
           return $str;
          }
       }
    }
    
    // and call it in order given below ...
    
    $obj = new ParentClass;
    
    echo '<br />$obj->mymethod()<br />';
    echo $obj->mymethod();
    
    echo '<br />$obj->mymethod(null,"test") <br />';
    echo $obj->mymethod(null,'test');
    
    echo '<br /> $obj->mymethod("test","test","test")<br />';
    echo $obj->mymethod('test','test','test');
    
    0 讨论(0)
提交回复
热议问题