Storing Functions in PHP Arrays
Storing functions in PHP arrays allows for more flexibility and dynamic code execution. However, the syntax provided in the question is outdated and not recommended.
Anonymous Functions
The most preferred method is to use anonymous functions:
<code class="php">$functions = [ 'function1' => function ($echo) { echo $echo; } ];</code>
Declared Function Names
If the function has already been declared, you can simply use its name as a string:
<code class="php">function do_echo($echo) { echo $echo; } $functions = [ 'function1' => 'do_echo' ];</code>
Pre-PHP 5.3
If using PHP versions prior to 5.3, you can resort to create_function():
<code class="php">$functions = array( 'function1' => create_function('$echo', 'echo $echo;') );</code>
Usage
Regardless of the method chosen, the functions can be called directly or using call_user_func() or call_user_func_array():
<code class="php">$functions['function1']('Hello world!'); call_user_func($functions['function1'], 'Hello world!');</code>
Note: For PHP versions less than 5.3, consider upgrading to a later version for improved functionality and security.
The above is the detailed content of How to Store Functions in PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!