Exploring Array Storage of Functions in PHP
PHP offers several options for storing functions in arrays, each with its own implications.
Anonymous Functions
The preferred approach is to use anonymous functions:
<code class="php">$functions = [ 'function1' => function ($echo) { echo $echo; } ];</code>
Anonymous functions allow you to define a function on-the-fly, without declaring it beforehand.
Referencing Named Functions
If you want to store an existing function, you can reference it by name as a string:
<code class="php">function do_echo($echo) { echo $echo; } $functions = [ 'function1' => 'do_echo' ];</code>
This method involves declaring the function outside of the array.
Legacy Approach (PHP < 5.3)
For older versions of PHP that do not support anonymous functions, you can use create_function:
<code class="php">$functions = array( 'function1' => create_function('$echo', 'echo $echo;') );<p>However, this approach is deprecated and should be avoided if possible.</p> <p><strong>Invoking Stored Functions</strong></p> <p>Regardless of the storage method used, you can invoke the functions directly (PHP >= 5.4) or with call_user_func/call_user_func_array:</p> <pre class="brush:php;toolbar:false"><code class="php">$functions['function1']('Hello world!'); call_user_func($functions['function1'], 'Hello world!');</code>
The above is the detailed content of How Do You Store Functions in an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!