【发布时间】:2017-05-23 07:44:20
【问题描述】:
我使用的是这样的代码:
$a = [];
$a['a'] = 1;
$text1 = [];
foreach ($b as $item)
{
$text1[] = $item['1'];
}
$a['text1'] = implode(',', $text1);
$text2 = [];
foreach ($b as $item)
{
$text2[] = $item['2'];
}
$a['text2'] = implode(',', $text2);
我的同事这样改写它:
$a = [];
$a['a'] = 1;
$a['text1'] = call_user_func(function() use ($b) {
$text1 = [];
foreach ($b as $item)
{
$text1[] = $item['1'];
}
return implode(',', $text1);
}();
$a['text2'] = call_user_func(function() use ($b) {
$text2 = [];
foreach ($b as $item)
{
$text2[] = $item['2'];
}
return implode(',', $text2);
}();
他的原因:它增加了封装性,在我的第一个示例中,除非我取消设置它们,否则会有“漫游”变量($text1、$text2)。
【问题讨论】:
-
这和 Clojure 有什么关系。那个标签是
closure的错字吗? -
$a['text1'] = implode(',', array_column($b, '1'));呢? -
call_user_func的语法错误。应该是call_user_func(function(){...});你最后多了一个(。 -
简而言之,你的同事说的有道理。但是,它们的更改只是朝着正确封装对象迈出的一小步,该对象应同时包含
$b和刚刚创建的闭包(作为方法)。 -
在第二段代码中
call_user_func()的使用非常错误,尤其是因为它以几乎相同的方式重复了第二次。一次使用普通函数要好得多。