zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    python连接字符串的几种方法--转子(香草拿铁的园子)
    winform属性
    C# Timer
    SQL基础
    SQL 基础
    File类 ReadAllBytes() ReadAllLines() ReadAllText()
    学习C#20天有感
    装箱和拆箱
    机器学习基础:朴素贝叶斯小结
    分类问题样本不均衡问题
  • 原文地址:https://www.cnblogs.com/njr8/p/4981878.html
Copyright © 2011-2022 走看看