Storing Functions in PHP Arrays
In PHP, it is possible to store functions within arrays. This can be beneficial for organizing and accessing functions dynamically in your code.
Anonymous Functions
The recommended approach is to use anonymous functions, which can be stored directly in arrays. An anonymous function is created using this syntax:
function ($args) { // Function body }
For example:
<code class="php">$functions = [ 'function1' => function ($echo) { echo $echo; } ];</code>
Pre-Declared Functions
If you want to store a function that has already been declared, you can simply refer to it by name as a string:
<code class="php">function do_echo($echo) { echo $echo; } $functions = [ 'function1' => 'do_echo' ];</code>
Using create_function
In older versions of PHP (before 5.3), anonymous functions were not supported. In such cases, you can use the deprecated create_function function:
<code class="php">$functions = array( 'function1' => create_function('$echo', 'echo $echo;') );</code>
Accessing and Calling Stored Functions
Once functions are stored in an array, they can be called either directly (PHP >= 5.4) or using call_user_func or call_user_func_array functions:
<code class="php">$functions['function1']('Hello world!'); call_user_func($functions['function1'], 'Hello world!');</code>
Conclusion
The ability to store functions in PHP arrays provides flexibility and organization in code. Anonymous functions, pre-declared function references, and create_function (deprecated) offer different ways to achieve this.
The above is the detailed content of How Do You Store and Call Functions Within PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!