在创建匿名PHP函数的过程中呈现变量 [英] Render a variable during creation of anonymous PHP function

查看:67
本文介绍了在创建匿名PHP函数的过程中呈现变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用匿名函数获得一个简单的排序函数.分别对asc和desc进行排序.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆