Storing Functions in PHP Arrays
The question arises whether it is possible to store functions within PHP arrays. For instance, consider the following:
$functions = [ 'function1' => function($echo) { echo $echo; } ];
Is this a viable approach? If not, what are the recommended alternatives?
Recommended Approach: Anonymous Functions
The preferred method for storing functions in arrays involves utilizing anonymous functions. Like the example above, they can be defined inline:
$functions = [ 'function1' => fn($echo) => $echo ];
Referencing External Functions
When dealing with pre-declared functions, you can reference them by name as strings:
<code class="php">function do_echo($echo) { echo $echo; } $functions = [ 'function1' => 'do_echo' ];</code>
Legacy Method (PHP < 5.3): create_function
For older versions of PHP that do not support anonymous functions, the create_function construct can be employed:
<code class="php">$functions = [ 'function1' => create_function('$echo', 'echo $echo;') ];<p><strong>Calling Stored Functions</strong></p> <p>Regardless of the method used to store the function, it can be invoked directly (PHP >= 5.4) or through 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>
In summary, anonymous functions are the recommended approach for storing functions in PHP arrays, with string references being used for pre-declared functions and create_function being available for legacy PHP versions.
The above is the detailed content of How can I store functions in PHP arrays effectively?. For more information, please follow other related articles on the PHP Chinese website!