我需要将$ route传递给它的内部函数,但是失败了:
function compilePath( $route )
{
preg_replace( '$:([a-z]+)$i', 'pathOption' , $route['path'] );
function pathOption($matches)
{
global $route;//fail to get the $route
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用php5.3,是否有一些功能可以帮助?
我不认为你可以在PHP 5.2中做任何类似的事情,但不幸的是 - 当你使用PHP 5.3时......你可以使用Closures来实现它.
首先,这是一个使用Closure的简单示例:
function foo()
{
$l = "xyz";
$bar = function () use ($l)
{
var_dump($l);
};
$bar();
}
foo();
Run Code Online (Sandbox Code Playgroud)
将显示:
string 'xyz' (length=3)
Run Code Online (Sandbox Code Playgroud)
注意use关键字;-)
以下是您在特定情况下如何使用它的示例:
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);
Run Code Online (Sandbox Code Playgroud)
你得到这个输出:
array
0 => string ':blah' (length=5)
1 => string 'blah' (length=4)
array
'path' => string 'test:blah' (length=9)
Run Code Online (Sandbox Code Playgroud)
几个笔记:
preg_replace_callback,而不是preg_replace- 因为我想调用一些回调函数.$route使用new use关键字导入匿名函数.
preg_replace_callback给回调函数,而且$route.