php array_map回调参数范围 [英] php array_map callback parameter scope

查看:70
本文介绍了php array_map回调参数范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,传递给wrap_map的回调函数在外部函数中看不到参数,为什么? (有关详细信息,请参见代码注释)

In the following code the callback function passed to wrap_map can't see the argument in the outer function, why? (see code comment for detail)

public static function wrap_implode($ar, $wrap, $delim){
  echo "wrap is $wrap"; //wrap is ok
  $res = array_map(function($val){
     echo "wrap is $wrap"; //wrap is not set here!
     return $wrap. $val . $wrap;
   }, $ar);

   return implode($delim, $res);
}

推荐答案

因为它在另一个作用域中.如果要使用$wrap,请尝试:

Because it is in another scope. If you want to use $wrap, try:

function($val) use ($wrap){
   //etc
}

当然,这里的函数不需要回调:

Of course, your function here doesn't need a callback:

return $wrap.implode($wrap.$delim.$wrap,$ar).$wrap;

这篇关于php array_map回调参数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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