以编程方式编写函数的关联数组

Programmatically write an associative array of functions

我有很多函数存储在这样的关联数组中:

$arr['my-title'] = function(){process(146,'My Title');};
$arr['un-cafe-chaud'] = function(){process(857,'Un café chaud');};
$arr['vpn'] = function(){process(932,'VPN');};
$arr['another-example'] = function(){process(464,'Another example');};

目前我必须手动对每个键进行编码。

由于键名是标题的函数,我想将其自动化。

 function assign_keys($title,$id){
$u=str_replace(array(' ','é'),array('-','e'),strtolower($title));
$arr[$u] = function(){process($id,$title);};
}

但它不起作用,因为处理函数无法获得 $id$title 值。

如果能帮助我解决这个问题,我将不胜感激!谢谢你。

您可能需要一个引用 & 来获取函数外部的数组,并 use 将变量获取到闭包中:

function assign_keys($title, $id, &$arr){
    $u = str_replace(array(' ','é'), array('-','e'), strtolower($title));
    $arr[$u] = function() use($title, $id) { process($id, $title); };
}

assign_keys('My Title', 146, $arr);

首先,您应该将 $arr 作为参数传递给函数,以便能够对其进行变异。其次,您应该使用 use 使这两个变量在匿名函数中可用,如下所示:

function assign_keys($title,$id, &$arr){
    $u=str_replace(array(' ','é'),array('-','e'),strtolower($title));
    $arr[$u] = function() use ($id, $title){process($id,$title);};
}

然后像这样使用它:

$arr = [];

assign_keys('Some title', 123, $arr);

var_dump($arr);

这应该打印:

array(1) {
  ["some-title"]=>
  object(Closure)#1 (1) {
    ["static"]=>
    array(2) {
      ["id"]=>
      int(123)
      ["title"]=>
      string(10) "Some title"
    }
  }
}