Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return anonymous functions

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.

like image 236
jcklie Avatar asked Mar 03 '12 13:03

jcklie


2 Answers

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.

like image 50
Tim Lytle Avatar answered Oct 03 '22 23:10

Tim Lytle


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.

like image 21
nickf Avatar answered Oct 03 '22 23:10

nickf