1

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);
}
Matt.Z
  • 602
  • 7
  • 19
  • possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – deceze May 08 '14 at 07:56
  • Yup, but this question title is too hard to find.. – Matt.Z May 08 '14 at 08:41

2 Answers2

1

The use will do the job..

function my_func($text, $prefix){
    $regex = '/xxxx/';
    return preg_replace_callback($regex, function($matches) use(&$prefix){ 
                                                          //^^^^^^^^^^^^^
     }, $text);
}
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

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);
}
Matt.Z
  • 602
  • 7
  • 19