PHP: How to make variable visible in create_function()?

社会主义新天地 提交于 2019-12-20 07:12:57

问题


This code:

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

How to make $t visible from create_function() in preg_replace() function?


回答1:


An anonymous function would work, while making use of the use syntax:

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



回答2:


You can't make the variable accessible, but in your case you can just use the value:

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

However, it is highly recommended you use the function($matches) use ($t) {} syntax here (http://php.net/functions.anonymous).

And there is eval modifier for preg_replace:

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

But I have the feeling that your function is using the wrong operator here anyway - or the wrong pattern / subpattern.




回答3:


Same way you make any function see a global variable.

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



回答4:


You can use $GLOBALS but its not highly recomended ...

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

Better Solution

http://php.net/functions.anonymous anonymous function .. if you don't like to use that you can also do array_walk ( http://php.net/manual/en/function.array-walk.php ) after you have gotten the result in an array format then pass $t as a proper function argument




回答5:


in anonymous just use the keyword use or global in create_function use global

function() use($var1,$var2...etc){code here}

or

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



来源:https://stackoverflow.com/questions/10131335/php-how-to-make-variable-visible-in-create-function

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