What is PHP function overloading for?

前端 未结 3 1316
死守一世寂寞
死守一世寂寞 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: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 
    '; } else{ $str = ''; if( $arg1 != null ) $str .= "arg1 = ".$arg1."
    "; if( $arg2 != null ) $str .= "arg2 = ".$arg2."
    "; if( $arg3 != null ) $str .= "arg3 = ".$arg3."
    "; return $str; } } } // and call it in order given below ... $obj = new ParentClass; echo '
    $obj->mymethod()
    '; echo $obj->mymethod(); echo '
    $obj->mymethod(null,"test")
    '; echo $obj->mymethod(null,'test'); echo '
    $obj->mymethod("test","test","test")
    '; echo $obj->mymethod('test','test','test');

提交回复
热议问题