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

  • 相关阅读:
    Spring IOC -bean对象的生命周期详解
    @RequestBody 和@ResponseBody 注解详解
    SpringMVC访问静态资源的三种方式
    servlet的url-pattern匹配规则详细描述
    SpringMVC POJO入参过程分析
    SpringMVC @ModelAttribute详解
    SpringMVC @SessionAttributes注解
    SpringMVC 向页面传值-Map、Model和ModelMap
    SpringMVC 向前台页面传值-ModelAndView
    SpringMVC 使用Servlet原生API作为参数
  • 原文地址:https://www.cnblogs.com/lpblogs/p/7389372.html
Copyright © 2020-2023  润新知