Question

I noticed that PHP now can use temp function definition (like js and other scripts language), but how can I get local variable in the temp function ?

ex:

function my_func($text, $prefix){
    $regex = '/xxxx/';
    return preg_replace_callback($regex, function($matches){
         // how to read $prefix here?
     }, $text);
}
Was it helpful?

Solution

The use will do the job..

function my_func($text, $prefix){
    $regex = '/xxxx/';
    return preg_replace_callback($regex, function($matches) use(&$prefix){ 
                                                          //^^^^^^^^^^^^^
     }, $text);
}

OTHER TIPS

I find it ..

http://www.php.net/manual/en/functions.anonymous.php

function my_func($text, $prefix){
    $regex = '/xxxx/';
    return preg_replace_callback($regex, function($matches) use ($prefix){
         // how to read $prefix here?
     }, $text);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top