PHP如何实现函数重载

众所周知,PHP是一种松散类型语言,故而不支持函数重载(区别于函数覆盖)。可是今天我在看Exception的时候,发现Exception的构造器有重载,可以如下调用:

  1. throw new Exception("Something bad just happened", 4);
  2. throw new Exception("Something bad just happened");
  3. 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()函数的使用。

转载于:https://my.oschina.net/xue777hua/blog/117770

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值