最重要的一句话:闭包函数继承变量的值的时候,是闭包函数定义的时候,而不是闭包函数被调用的时候。
php中,匿名函数也叫闭包函数,直接在function传入变量即可。使用时将函数当做变量使用。
例如:
$cl = function($name){
return sprintf('hello %s',name);
}
echo $cli('fuck');
php中使用use来配合匿名函数的使用:
$message = 'hello';
$example = function() use ($message){
var_dump($message);
};
echo $example();//输出hello
$message = 'world';
echo $example();//输出hello 因为**继承变量的值的时候是闭包函数定义的时候而不是闭包函数被调用的时候**
从上面例子看到,匿名函数的特性是:继承变量的值的时候,是闭包函数定义的时候,而不是闭包函数被调用的时候
那有什么办法来改变这种情形,让闭包函数继承的变量的值的时候,是闭包函数被调用的时候,而不是函数定义的时候呢??答案是用use+变量引用,如下例:
$message = 'hello';
$example = function() use(&$message){//此处传引用
var_dump($message);
};
echo $example();//输出hello
$message = 'world';
echo $example();//此处输出world
闭包函数也用于正常的传值,如:
//闭包函数也用于正常的传值
$message = 'hello';
$example = function ($data) use ($message){
return "{$data},{$message}";
};
echo $example('world');
网友评论