zoukankan      html  css  js  c++  java
  • php回调函数的概念及实例

    php提供了两个内置函数call_user_func()和call_user_func_array()提供对回调函数的支持。
    这两个函数的区别是call_user_func_array是以数组的形式接收回调函数的参数的,
    看它的原型就知道了:mixed call_user_func_array ( callable $callback,array$param_arr ),它只有两个参数。
    而call_user_func($callback,参数1,参数2,…)的参数个数根据回调函数的参数来确定的。

       如何实现对脚本中全局函数、类中未使用$this的非静态方法、类中使用$this的非静态方法(需要传入对象)、类中静态方法的回调呢,下面是测试通过的代码。

            <?php   
    
            //普通函数  
            function f1($arg1,$arg2)  
            {  
                echo __FUNCTION__.'exec,the args is:'.$arg1.' '.$arg2;  
                echo "<br/>";  
            }  
              
            //通过call_user_func调用函数f1  
            call_user_func('f1','han','wen');  
          
                //通过call_user_func_array调用函数  
            call_user_func_array('f1',array('han','wen'));  
            class A  
            {  
                public $name;  
          
                function show($arg1)  
                {  
                    echo 'the arg is:'.$arg1."<br/>";  
                    echo 'my name is:'.$this->name;  
                    echo "<br/>";  
                }  
                function show1($arg1,$arg2)  
                {  
                    echo __METHOD__.' exec,the args is:'.$arg1.' '.$arg2."<br/>";  
                }  
                public static function show2($arg1,$arg2)  
                {  
                    echo __METHOD__.' of class A exec, the args is:'.$arg1.' '.$arg2."<br/>";  
                }  
          
            }  
            //调用类中非静态成员函数,该成员函数中有$this调用了对象中的成员  
            $a = new A;  
            $a->name = 'wen';         
            call_user_func_array(array($a,'show',),array('han!'));
        
            //调用类中非静态成员函数,没有对象被创建,该成员函数中不能有$this
            call_user_func_array(array('A','show1',),array('han!','wen'));  
     
            //调用类中静态成员函数
            call_user_func_array(array('A','show2'),array('argument1','argument2'));
    原文:https://blog.csdn.net/u010544319/article/details/9186323 
  • 相关阅读:
    报错18:28:21: Debugging starts QLayout: Attempting to add QLayout ““ to MainWindow “MainWindow“, which
    春 景
    sysTime(系统毫秒)
    balabala视频格式转换器
    tasklist /FI命令结论
    QFileSystemWatcher
    Qfileinfo
    Qdir
    欢迎光临我的普吉岛芭东海滩公寓
    使用ArcGIS GP服务之一框架介绍
  • 原文地址:https://www.cnblogs.com/sgm4231/p/10457415.html
Copyright © 2011-2022 走看看