I want to have a function written in PHP which can create anonymous functions which ~5 parameters and return them so I can store them in a key/value array and call them later without any knowledge about the parameters given and more than once.
E.g.
$fun();
How do I achieve the returning and the reusable calling afterwards?
Thanks in advance.
You mean something like this?
<?php
function setData($user, $pass, $host){
return function() use ($user, $pass, $host){
return array($user, $pass, $host);
};
}
//set the data once
$container = setData('test', 'password', 'localhost');
//use the function without passing the data again (and it should be noted, you
//can't set the data again)
var_dump($container());
And the output:
array(3) { [0]=> string(4) "test" [1]=> string(8) "password" [2]=> string(9) "localhost" }
Not sure of your use case, but for my example the output of the function could be a formatted DNS as well as the simple arrays.
As mentioned elsewhere, func_get_args would make this work with any number of arguments.
Take a look at http://php.net/manual/en/functions.anonymous.php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
The $greet
variable could be returned by another function if you need.
The other thing you might need to look at is func_get_args()
for reading the arbitrary argument list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With