众所周知,PHP是一种松散类型语言,故而不支持函数重载(区别于函数覆盖)。可是今天我在看Exception的时候,发现Exception的构造器有重载,可以如下调用:
- throw new Exception("Something bad just happened", 4);
- throw new Exception("Something bad just happened");
- throw new Exception("",4);
显然,上述方式就是重载。故而PHP中是可以实现函数重载的,那么它是如何实现的呢?寻思了一会儿,既然PHP弱类型,无法根据函数参数的类型来识别函数,但是我们可以统计函数参数的个数啊!于是依据此思路,有了以下代码:
ClassTest.php文件代码
1 <? php 2 class ClassTest{ 3 4 public function fun( $x = null , $y = null ){ 5 if ( func_num_args () == 1 ){ 6 $this -> fun1( $x ); 7 } 8 if ( func_num_args () == 2 ){ 9 $this -> fun2( $x , $y ); 10 } 11 } 12 13 private function fun1( $x ){ 14 echo " fun1 is called!\t\$x= $x <br/> " ; 15 } 16 17 private function fun2( $x , $y ){ 18 echo " fun2 is called!\t\$x= $x \t\$y= $y <br/> " ; 19 } 20 21 public function funWithoutParam(){ 22 $temp = " funWithoutParam " . func_num_args (); 23 $this -> $temp (); 24 } 25 26 private function funWithoutParam1(){ 27 echo " funWithoutParam1 is called!<br/> " ; 28 } 29 private function funWithoutParam2(){ 30 echo " funWithoutParam2 is called!<br/> " ; 31 } 32 } 33 ?>
index.php文件代码
1 <? php 2 function __autoload( $className ){ 3 require_once $className . ' .php ' ; 4 } 5 6 $test = new ClassTest(); 7 // overload with parameters 8 $test -> fun( 1 ); 9 $test -> fun( 1 , 2 ); 10 11 // overload without parameters 12 $test -> funWithoutParam( 1 ); 13 $test -> funWithoutParam( 1 , 2 ); 14 ?>
从上述代码中可以看出,主要得益于func_num_args()函数的使用。