简体   繁体   中英

How to pass parameters dynamically in PHP?

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?

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 .

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM