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

时间:2017-03-21 19:43:27

标签: php key associative-array

我有很多函数存储在关联数组中,如下所示:

$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');};

目前我必须手动编码每个密钥。

由于键名是Title的功能,我想自动化它。

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

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

任何有关如何处理此问题的帮助都将受到高度赞赏!谢谢。

2 个答案:

答案 0 :(得分:0)

您可能希望引用&将数组放在函数外部,并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);

答案 1 :(得分:0)

首先,您应该将$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"
    }
  }
}