Render a variable during creation of anonymous PHP

2020-04-17 07:29发布

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 param to uasort().

1条回答
够拽才男人
2楼-- · 2020-04-17 07:50

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
};
查看更多
登录 后发表回答