例如:
<?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)
本文为big4ever.com原创文章,转载无需和我联系,但请注明来自www.big4ever.com
最新评论