php回调函数的概念及实例

摘要:php提供了两个内置函数call_user_func()和call_user_func_array()提供对回调函数的支持。这两个函数的区别是call_user_func_array是以数组的形式接收回调函数的参数的。而call_user_func($callback,参数1,参数2,…)的参数个数根据回调函数的参数来确定的。

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


PHP回调函数4种写法

<?php 
//1.匿名函数
 
$serv->on('Request',function($req,$resp){
	echo "hello world";
});
 
// 2.类静态方法
class A
{
	static function test($req,$resp)
	{
		echo "hello world";
	}
}
 
$serv->on('Request','A::Test');
$serv->on('Request',array('A','Test'));
 
//3.函数
 
function my_onRequest()
{
	echo "hello world";
}
 
$serv->on('Request','my_onRequest');
 
 
 
// 4.对象方法
class A
{
	function test($req,$resp)
	{
		echo "hello world";
	}
}
 
$object = new A();
$server->on('Request',array($object,'test'));


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_2185