Reputation: 12542
In PHP there is a function called extract
, which takes an array, and transforms your data into PHP variables. This function is very useful when I need to send variables to an include. Ex.
extract(array( "test" => 123 ));
require "test.php"
So test.php: print($test);
Returns: 123
I need to do the same with functions (which I may not know). PHP 5.4 has support for use
(Anonymous Function), which is quite interesting. Ex.
$test = 123;
call_user_func(function() use($test) {
print($test);
});
However, I need to pass variables with other names and amounts. Something like:
$useArgs = array( "a" => 1, "b" => 2, "c" => 3 );
call_user_func(function() use(extract($useArgs)) {
print($a);
print($b);
print($c);
if(isset($d)) {
print($d);
}
});
How is this possible?
Upvotes: 1
Views: 358
Reputation: 19466
Just call extract()
from inside your function
$useArgs = array( "a" => 1, "b" => 2, "c" => 3 );
call_user_func(function() use($useArgs) {
extract($useArgs);
print($a);
print($b);
print($c);
if(isset($d)) {
print($d);
}
});
Upvotes: 2