Можно ли сохранить функцию в массиве PHP?

В Windows это является собственным с API Win32...

61
задан Kirk Ouimet 30 September 2009 в 18:25
поделиться

2 ответа

There are a few options. Use create_function:

$functions = array(
  'function1' => create_function('$echo', 'echo $echo;')
);

Simply store the function's name as a string (this is effectively all create_function is doing):

function do_echo($echo) {
    echo $echo;
}

$functions = array(
  'function1' => 'do_echo'
);

If you are using PHP 5.3 you can make use of anonymous functions:

$functions = array(
  'function1' => function($echo) {
        echo $echo;
   }
);

All of these methods are listed in the documentation under the callback pseudo-type. Whichever you choose, the recommended way of calling your function would be with either the call_user_func or call_user_func_array function.

call_user_func($functions['function1'], 'Hello world!');
140
ответ дан 24 November 2019 в 17:05
поделиться

To follow up on Alex Barrett's post, create_function() returns a value that you can actually use to call the function, thusly:

$function = create_function('$echo', 'echo $echo;' );
$function('hello world');
9
ответ дан 24 November 2019 в 17:05
поделиться