PHP implements function overloading instances using func_get_args and func_num_args functions

  • 2021-08-03 09:27:32
  • OfStack

In this paper, the method of PHP using func_get_args and func_num_args functions to realize function overloading is illustrated. Share it for your reference. Specific methods are analyzed as follows:

Friends who learn php know that php itself does not have function overloading, let alone using methods like java and c. However, if we have a deep understanding of 1, we will find that func_get_args () and func_num_args () functions can be used to realize function overloading in php. Here are two examples of function overloading. These two functions realize function overloading.

1. Default parameters. If this is not a required parameter in a function, and the corresponding default value is added, the corresponding function can be completed. The code is as follows:

function overloadFun($param1, $param2 = '1',$param3 = true)  

 // do something  
}

Using the functions func_get_args () and call_user_func_array (), the code for PHP is as follows:
function rewrite() {     
$args = func_get_args();    
if(func_num_args() == 1) {    
func1($args[0]);    
} else if(func_num_args() == 2) {    
func2($args[0], $args[1]);    
}    
}    
   
function func1($arg) {    
echo $arg;    
}    
   
function func2($arg1, $arg2) {    
echo $arg1, ' ', $arg2;    
}    
   
rewrite('PHP'); // Call func1    
rewrite('PHP','China'); // Call func2

2. Use the default value to get the desired result according to the input. The code is as follows:
function test($name=" Xiao Li ",$age="23"){    
echo $name."  ".$age;   
}   
test();   
echo "<br/>";   
test("a");   
echo "<br/>";   
test("a","b");

3. Use the __call ($name, $arg) function for processing, and the code is as follows:
<?php  
class OverLoad{ 
function __call($name, $args) 

  if($name=='overloadFun') 
  { 
   switch(count($args)) 
   { 
    case 0: $this->overloadFun0();break; 
    case 1: $this->overloadFun1($args[0]); break; 
    case 2: $this->overloadFun2($args[0], $args[1]); break; 
    default: //do something 
      break; 
   } 
  } 

    
function overloadFun0() 

  echo 0; 
}  function overloadFun1($var1) 

  echo $var1; 
}  function overloadFun2($var1,$var2) 

   
  echo $var1+$var2; 
   } 
}   
$test=new OverLoad(); 
$test->overloadFun()."<br />".  
$test->overloadFun(1)."<br />".  
$test->overloadFun(1,2)."<br />"; 
?>

With such methods, we can use them to realize simple function overloading, but one point to note is that php, as a weakly typed language, cannot directly realize overloading like strong types such as java and c + +, at least now, we don't know if there will be any future versions.

I hope this article is helpful to everyone's PHP programming.


Related articles: