php实现函数重载

时间:2023-03-09 22:06:58
php实现函数重载

java、.net等强类型预言中都有方法重载,但是PHP是弱类型语言,不能确定参数的类型,

而且如果php定义的方法接收一个参数,调用的时候传入多个也不会有问题,所以不能进行重载。

但是我们可以通过php提供的魔术方法__call来模拟实现方法重载。如下代码示例:

<?php

class test{
function __call($method,$args){
if($method == 'method'){
$argCount = count($args);
$functionName = 'method'.$argCount;
if(method_exists($this,$functionName)){
call_user_func_array(array($this,$functionName),$args);
}
}
} function method1($a){
echo '我是一个 参数的方法';
} function method2($a,$b){
echo '我是二个 参数的方法';
} function method3($a,$b,$c){
echo '我是三个 参数的方法';
} function method4($a,$b,$c,$d){
echo '我是四个 参数的方法';
}
} $test = new test(); //输出 “我是一个 参数的方法”
$test->method(1); //输出 “我是二个 参数的方法”
$test->method(1,2); //输出 “我是三个 参数的方法”
$test->method(1,2,3); //输出 “我是四个 参数的方法”
$test->method(1,2,3,4);