ホームページ  >  記事  >  バックエンド開発  >  preg_replace_callback 中 function($match) use ($ten), 里面的 use 是什么意义

preg_replace_callback 中 function($match) use ($ten), 里面的 use 是什么意义

WBOY
WBOYオリジナル
2016-06-13 12:12:511033ブラウズ

preg_replace_callback 中 function($match) use ($ten), 里面的 use 是什么意思

$string = "Some numbers: one: 1; two: 2; three: 3 end";<br />$ten = 10;<br />$newstring = preg_replace_callback(<br />    '/(\\d+)/',<br />    function($match) use ($ten) { return (($match[0] + $ten)); },<br />    $string<br />    );<br />echo $newstring; 

------解决思路----------------------
use 中文释义 使用

function($match) use ($ten) { return (($match[0] + $ten)); }
让变量 $ten 在匿名函数中可以被使用

相当于
$ten = 10;
function foo($match) {
  global $ten;
  return (($match[0] + $ten));
}
不过如果 $ten 不是全局变量的话就有麻烦了
------解决思路----------------------
php 5.3新增的闭包语法

闭包函数(匿名函数)可以从父作用域中继承变量   任何此类变量都应该用 use 语言结构传递进去


------解决思路----------------------
5.2  不能用你可以这样
$string = "Some numbers: one: 1; two: 2; three: 3 end";<br />$ten = 10;<br />$newstring = preg_replace_callback(<br />    '/(\\d+)/',<br />    create_function('$match', "return \$match[0] + $ten;"),<br />    $string<br />    );<br />echo $newstring;

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。