开发者

php array_map callback parameter scope

开发者 https://www.devze.com 2023-02-20 22:52 出处:网络
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)

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 $wra开发者_高级运维p. $val . $wrap;
   }, $ar);

   return implode($delim, $res);
}


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消