Reputation: 63636
I need to pass the $route to its inner function,but failed:
function compilePath( $route )
{
preg_replace( '$:([a-z]+)$i', 'pathOption' , $route['path'] );
function pathOption($matches)
{
global $route;//fail to get the $route
}
}
I'm using php5.3,is there some feature that can help?
Upvotes: 1
Views: 668
Reputation: 401002
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.
function foo()
{
$l = "xyz";
$bar = function () use ($l)
{
var_dump($l);
};
$bar();
}
foo();
Will display :
string 'xyz' (length=3)
Notice the use
keyword ;-)
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 :
preg_replace_callback
, and not preg_replace
-- as I want some callback function to be called.$route
, with the new use
keyword.
preg_replace_callback
to the callback function, and the $route
.Upvotes: 5
Reputation: 468
Put everything in a class, including the callback and grab $route using $this->route instead of using globals. You should be using preg_replace_callback(). To use a callback from a class use Array($class,'callback') or Array('className','callback).
Upvotes: 1