I don't think you can do anything like that in PHP 5.2, unfortunatly -- but as you are using PHP 5.3... you could use Closures to get that to work.
To begin, here's a quick example of using a Closure :
function foo()
{
$l = "xyz";
$bar = function () use ($l)
{
var_dump($l);
};
$bar();
}
foo();
Will display :
string 'xyz' (length=3)
Notice the use
keyword ;-)
And here's an example of how you could use that in your specific case :
function compilePath( $route )
{
preg_replace_callback( '$:([a-z]+)$i', function ($matches) use ($route) {
var_dump($matches, $route);
} , $route['path'] );
}
$data = array('path' => 'test:blah');
compilePath($data);
And you'd get this output :
array
0 => string ':blah' (length=5)
1 => string 'blah' (length=4)
array
'path' => string 'test:blah' (length=9)
A couple of notes :
- I used
preg_replace_callback
, and not preg_replace
-- as I want some callback function to be called.
- I'm using an anonymous function as callback
- And that anonymous function is importing
$route
, with the new use
keyword.
- Which means that, in my callback function, I can access both the matches, which are always passed by
preg_replace_callback
to the callback function, and the $route
.