PHP function overloading

前端 未结 10 976
北恋
北恋 2020-11-22 17:24

Coming from C++ background ;)
How can I overload PHP functions?

One function definition if there are any arguments, and another if there are no arguments? Is it

10条回答
  •  渐次进展
    2020-11-22 17:38

    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');

提交回复
热议问题