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

WBOY
풀어 주다: 2016-06-23 13:42:24
원래의
1076명이 탐색했습니다.

$string = "Some numbers: one: 1; two: 2; three: 3 end";$ten = 10;$newstring = preg_replace_callback(    '/(\\d+)/',    function($match) use ($ten) { return (($match[0] + $ten)); },    $string    );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 语言结构传递进去

use 中文释义 使用

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

相当于
$ten = 10;
function foo($match) {
global $ten;
return (($match[0] + $ten));
}
不过如果 $ten 不是全局变量的话就有麻烦了



5.2中可以替换吗?
如果不是全局变量可以就不能做了吗?$ten;

php 5.3新增的闭包语法

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


5.2不能用吗? 没有替换方法吗?

5.2 不能用你可以这样

$string = "Some numbers: one: 1; two: 2; three: 3 end";$ten = 10;$newstring = preg_replace_callback(    '/(\\d+)/',    create_function('$match', "return \$match[0] + $ten;"),    $string    );echo $newstring;
로그인 후 복사
로그인 후 복사

5.2 不能用你可以这样

$string = "Some numbers: one: 1; two: 2; three: 3 end";$ten = 10;$newstring = preg_replace_callback(    '/(\\d+)/',    create_function('$match', "return \$match[0] + $ten;"),    $string    );echo $newstring;
로그인 후 복사
로그인 후 복사


谢谢 , 
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!