[英]How to pass parameters dynamically in PHP?
I need to pass the $route to its inner function,but failed: 我需要将$ route传递给它的内部函数,但是失败了:
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? 我正在使用php5.3,是否有一些功能可以帮助您?
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. 不幸的是,我认为您无法在PHP 5.2中执行类似操作,但是当您使用PHP 5.3时...您可以使用Closures使其正常工作。
To begin, here's a quick example of using a Closure : 首先,这是一个使用Closure的简单示例:
function foo()
{
$l = "xyz";
$bar = function () use ($l)
{
var_dump($l);
};
$bar();
}
foo();
Will display : 将显示:
string 'xyz' (length=3)
Notice the use
keyword ;-) 注意
use
关键字;-)
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 : 一些注意事项:
preg_replace_callback
, and not preg_replace
-- as I want some callback function to be called. preg_replace_callback
,而不是preg_replace
,因为我想调用一些回调函数。 $route
, with the new use
keyword. $route
和新的use
关键字。
preg_replace_callback
to the callback function, and the $route
. preg_replace_callback
传递给回调函数,以及$route
。 Put everything in a class, including the callback and grab $route using $this->route instead of using globals. 将所有内容放在一个类中,包括回调,并使用$ this-> route而不是使用globals来获取$ route。 You should be using preg_replace_callback().
您应该使用preg_replace_callback()。 To use a callback from a class use Array($class,'callback') or Array('className','callback).
要使用来自类的回调,请使用Array($ class,'callback')或Array('className','callback)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.