开发者

Render a variable during creation of anonymous PHP function

I'm trying to get a simple sort function going using anonymous functions. One each for asc and desc sorting.

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]);

EDIT: I'm passing this array as a 开发者_如何学Goparam to uasort().


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
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜