php array_map callback parameter scope

☆樱花仙子☆ 提交于 2019-12-18 21:16:24

问题


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

回答1:


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;


来源:https://stackoverflow.com/questions/5505612/php-array-map-callback-parameter-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!