zoukankan      html  css  js  c++  java
  • php中动态调用函数call_user_func

    php中可使用call_user_func进行方法的动态调用,可以动态调用普通函数、类方法以及带参数的类方法
    1. 定义一个普通函数getCurrentDate,用于获取今天日期。
    call_user_func带上的参数为要被调用的函数名

    fucntion getCurrentDate(){
      echo 'getCurrentDate:' . date('Y-m-d');
    }
    call_user_func('getCurrentDate');

    程序会自动执行getCurrentDate函数并获得期望的结果
    getCurrentDate:2017-08-18

    2.定义一个类Test及类方法getS,call_user_func的输入参数变为一个数组,数组第一个元素为对象名、第二个元素为类方法名。
    class Test
    {    
        static public function getS()
        {
            echo "123";
        }
    }
    call_user_func(array('Test','getS'));

    ※ 注意:如果不加static,数据会出现,但是有可能会报错,例如:

    3.也可调用带参数的函数方法,此时将getA方法改为getA($a,$b).

    function getA($a,$b)
    {
        echo $a+$b;
    }
    call_user_func('getA','1','2');

    4.调用类中带参数的方法,此时将getS方法改为getS($a,$b,$c)

    class Test
    {
        static public function getS($a,$b,$c)
        {
            echo $a + $b+$c;
        }
    }
    call_user_func(array('Test','getS'),'123','123','123');

    ※ 如3 、4中,如果自动调用一个函数或者类中的方法,并且传递参数,只需在函数内加参数就行,传几个加几个;但是这样很乱,也可以写成:↓

    1)多参数自动调用函数:

    function getA($a,$b,$c)
    {
        echo $a+$b+$c;
    }
    call_user_func_array('getA') , array('123','123','123') );

    2)多参数自动调用类中方法

    class Test
    {
        static public function getS($a,$b,$c)
        {
            echo $a + $b+$c;
        }
    }
    call_user_func_array( array('Test','getS') , array('123','123','123') );

  • 相关阅读:
    gauss消元
    POJ1229 域名匹配
    HDU3487 play with chain
    POJ1185 炮兵阵地
    POJ2411
    sgu233 little kings
    树形DP初步-真树1662
    树形DP初步-二叉树1661
    c++——string类用法
    UVa1354 ——天平难题
  • 原文地址:https://www.cnblogs.com/lpblogs/p/7389372.html
Copyright © 2011-2022 走看看