2

I have a list of functions a(), b(), c()
I have a main() function.

Depending on case, I need to pass a different function to main() to use.
In javascript it would be:

var a = function(){}
var b = function(){}
var c = function(){}

var func = (some logic) a, b or c;

main(func);

How do I do that in php5.3?
I am trying to avoid using

$func_name = "a";
main($func_name){
   $func_name();
}

Or may be it is the best way, and I should not use closures of any type?

Jason
  • 15,017
  • 23
  • 85
  • 116
Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278

3 Answers3

2

Same idea in PHP 5.3, as you can create anonymous functions:

$sayHello = function($var)
{
    echo "Hello ", $var;
};

// Logic here to determine what $func is set to
$func = $sayHello;    

function callCustom($function)
{
    if(!is_callback($function))
    {
        // throw exception
    }
    $function("World");
}

callCustom($func);  // Hello World
0

Try this:

$a = function(){};
$b = function(){};
$c = function(){};

switch (rand(0, 2)) {
    case 0: $func = $a; break;
    case 1: $func = $b; break;
    case 2: $func = $c; break;
}

var_dump($func);

You can see a working example here http://codepad.viper-7.com/Ut5yGQ

Note: I used var_dump instead of main as main is undefined

Petah
  • 45,477
  • 28
  • 157
  • 213
0

In PHP, anything that is "callable" (is_callable­Docs) can be called (invoked). The manual often names these parameters as Callback, a pseudo-type in PHP­Docs.

You can use any of the different callbacks and pass them as a function parameter:

function main($callback)
{
    call_user_func($callback);
}

Then your function will work with any valid PHP callback.

Next to that, functions can be called with variables, some examples:

Variable Function Call:

  function name() {};
  $function = 'name'; # function name as string
  $function(); # invoke

Anonymous Function as Variable Function Call:

  $function = function() {}; # define function
  $function(); # invoke

See as well Variable Functions­Docs.

hakre
  • 193,403
  • 52
  • 435
  • 836