call_user_func调用对象的方法

函数作用:该函数主要用于通过函数名去调用该函数

例如:

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

上面的示例输出结果:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

call_user_func除了调用函数,还可以调用对象的方法

示例一
<?php
class T{
	public $t = 1;
    public function test($t){
		$this->t = $t;
        echo "hello world\n";
    }
}
$T = new T();
call_user_func(array($T, "test"),'t');
var_dump($T->t);

以上示例输出结果为:

hello world
string(1) "t"

示例二
<?php
class Food
{
    public $a = 1;
    function fail($a)
    {
        $this->a = $a;
    }
}
$food = new Food();
$food->fail(2);
echo $food->a;
echo PHP_EOL;
$handle = function ($b, $f) {
    var_dump($b);
    $f(3);
};
call_user_func($handle, 4, [$food, 'fail']);
var_dump($food->a);

call_user_func将被调用$hanbdle回调函数,后面的4会传值班给$b,$food实例的fail方法会传值给$f,$f()方法在handle内调用,即调用fail方法,从而改变$food内属性的值,以上示例输出结果为:

2
int(4)
int(3)

社交生活交流
请先登录后发表评论
  • latest comments
  • 总共0条评论