在创建匿名 PHP 函数期间呈现变量 [英] Render a variable during creation of anonymous PHP function
本文介绍了在创建匿名 PHP 函数期间呈现变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用匿名函数获得一个简单的排序函数.升序和降序排序各一个.
I'm trying to get a simple sort function going using anonymous functions. One each for asc and desc sorting.
是否可以在创建函数时立即呈现 $sortBy 变量,但仍然传递了 $x 和 $y在什么时候调用?我希望能够在创建这些时动态传入一个键.
Is it possible to render the $sortBy variable right away when the function is created, but still have $x and $y passed in when called later? I want to be able to dynamically pass in a key when creating these.
$sortBy = 'some_key';
// descending
$sort['desc'] = function($x, $y) {
if($x['data'][$sortBy] == $y['data'][$sortBy])
return 0;
return ($x['data'][$sortBy] > $y['data'][$sortBy]) ? -1 : 1;
};
uasort($arrayToSort, $sort[$order]);
我将此数组作为参数传递给 uasort().
I'm passing this array as a param to uasort().
推荐答案
您可以使用 在封闭范围内传递变量use
关键字(示例 #3 闭包和范围):
You can pass a variable in enclosing scope using the use
keyword (Example #3 Closures and scoping):
$sortBy = 'some_key';
$sort['desc'] = function($x, $y) use ($sortBy) {
// implementation
};
这篇关于在创建匿名 PHP 函数期间呈现变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文