call_user_func() 方法使用

call_user_func

(PHP 4, PHP 5, PHP 7)

call_user_func — 把第一个参数作为回调函数调用

说明:

call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) : mixed

第一个参数 callback 是被调用的回调函数,其余参数是回调函数的参数。请注意,传入call_user_func()的参数不能为引用传递。

1.通过函数的方式回调
<?php 
function barber($type){
    echo "you wanted a $type haircut, no problem\n";
}
call_user_func('barber','mushroom');
 ?>

返回内容如下:
you wanted a mushroom haircut, no problem

2.通过类名、对象的方式回调

<?php 
/**
 * 用call_user_func()来调用一个类里面的方法
 */
 
class myclass{
    static function say_hello(){
        echo "hello!\n";
    }
}
 
$classname = "myclass";
 
//通过数组键值的方式,对类名进行回调,回调类名里面的,say_hello方法
call_user_func(array($classname,'say_hello'));
 
//通过类名直接调用静态方法
call_user_func($classname .'::say_hello'); // As of 5.2.3// $myobject = new myclass();
 
//通过对象的方式回调
$myobject = new myclass();
call_user_func(array($myobject, 'say_hello'));
 
 ?>


//通过$this关键字进行对类的回调,以下源码出自thinkphp5 controller.php   200行

call_user_func([$this, $method]);

发布了142 篇原创文章 · 获赞 20 · 访问量 21万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章