美文网首页
Callback / Callable 类型

Callback / Callable 类型

作者: 幻无虚生 | 来源:发表于2019-05-25 11:00 被阅读0次

重载函数,和php的伪重载函数

  1. 重载函数
    a. c++允许在同一范围中声明几个功能类似的同名函数,但是这些同名函数的形参必须不同,也就是说同一个运算符完成不同的运算功能. 这就是重载函数.

  2. php 的伪重载函数 使用func_num_args() ; call_user_func_array(); func_get_arg();
    a 根据参数的不同来同一个函数在内部条用其他的函数. 应该属于工厂模式.

//函数重载
<?php

    function testOne($a)
    {

        echo(' 一个参数就这样 ');
    }

    function testTwo($a, $b)
    {
        echo(' 两个参数的就这样 ');
    }

    function testThree($a, $b, $c)
    {
        echo('这是三个参数的 ');
    }

    function test () {
        $argNum  =  func_num_args ();
        // 这一段其实可以用 $_arg = func_get_args() 来获得所有的参数,只是要用数组而已,不方便我下面的表达,呵呵
        for ( $i  =  0 ; $i  <  $argNum ; $i ++ ) {
            $key='_arg_'.$i;
            $$key=func_get_arg($i);
        }
        switch ( $argNum ) {
            case  1 :
                testOne( $_arg_0 );
                break ;
            case  2 :
                testTwo( $_arg_0,  $_arg_1 );
                break ;
            case  3 :
                testThree( $_arg_0,  $_arg_1,  $_arg_2 );
                break ;
            default :
                echo ( ' 这是没有参数的情况 ' );
                break ;
        }
    }

    call_user_func_array("test",[1,2,3]);
  1. 对象重载
    a. 在使用类重载调用方法的时候 是传递静态调用
<?php

class test2
{
    var $a = 0;
    var $b = 0;

    public static function test10()
    {
        $argNum = func_num_args();
        $_arg   = func_get_args();
        $res=0;
        switch ($argNum) {
            case  1 :
                $res=test2::test($_arg [0]);
                break;
            case  2 :
                $res=test2::test1($_arg [0], $_arg [1]);

                break;
            default :
                $res= '无限';
                break;
        }
        return $res;
    }

     private static function  test($a)
    {
        return  $a;

    }

    private static function test1($a, $b)
    {

        return $b;
    }
}

$a_object=call_user_func(['test2','test10'],'aaa');

/*$a_object=new test2();

$res=$a_object->test10('aaa','bbb');*/

echo ($a_object);

相关文章

网友评论

      本文标题:Callback / Callable 类型

      本文链接:https://www.haomeiwen.com/subject/vbcvzqtx.html