0

此代码:PHP:如何使变量在create_function()中可见?

$t = 100; 
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/", 
          create_function(
            '$matches', 
            'return $matches[1] + $t;' 
          ), $func); 

如何使$ T从的preg_replace()函数create_function()可见?

+1

您应该使用,而不是封'http://php.net/functions.anonymous功能($ matchtes)使用($ T){/*..*/}' – KingCrunch 2012-04-12 20:32:51

+0

嗯+操作上串? – hakre 2012-04-12 20:42:23

+1

@hakre''1“+ 100';)但是我明白了,你的意思是:正则表达式匹配以'Name'开头的东西,因此函数总是返回'100'('= $ t')。可能不想要。 – KingCrunch 2012-04-12 20:49:36

回答

3

anonymous function会的工作,同时利用该use语法:

$t = 100; 
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/", 
    function($matches) use($t) // $t will now be visible inside of the function 
    { 
     return $matches[1] + $t; 
    }, $func); 
0

相同的方式,使任何功能看到一个全局变量。

$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/", 
          create_function(
            '$matches', 
            'global $t; return $matches[1] + $t;' 
          ), $func); 
2

你不能让变量访问,但在你的情况,你可以只使用值:

$t = 100; 
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/", 
          create_function(
            '$matches', 
            'return $matches[1] + ' . $t .';' 
          ), $func); 

然而,强烈推荐您使用这里的function($matches) use ($t) {}语法(http://php.net/functions.anonymous )。

而且有EVAL修改为preg_replace

$str = preg_replace("/(Name[A-Z]+[0-9]*)/e", '$1+'.$t, $func); 

但是我有你的功能在这里使用了错误的操作反正感觉 - 或错误的模式/子模式。

+0

你是天才! – aztack 2014-08-24 11:05:08

0

您可以使用$GLOBALS,但它不是非常recomended ...

$str = preg_replace_callback ("/(Name[A-Z]+[0-9]*)/", create_function ('$matches', 'return $matches[1] + $GLOBALS["t"];'), $func); 

更好的解决方案

http://php.net/functions.anonymous匿名函数..如果你不喜欢用,你也可以做array_walkhttp://php.net/manual/en/function.array-walk.php )以数组格式获得结果后,通过$t作为适当的函数参数

0

以匿名形式使用关键字使用全球 在create_function使用全球

()函数使用($ VAR1,$ VAR2 ...等){代码在这里}

create_func($ args,'global $ var1,$ var2; code here;');

+0

当心! 'global'只从全局范围导入变量,而不是从函数定义的范围导入,比如'use'。 – 2015-08-10 14:35:04