首页 > Web开发 > 详细

php实现函数重载

时间:2015-11-20 19:54:09      阅读:245      评论:0      收藏:0      [点我收藏+]

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

 

php实现函数重载

原文:http://www.cnblogs.com/njr8/p/4981878.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!