Home > Article > Backend Development > Can Functions be Stored in PHP Arrays?
Storing Functions in PHP Arrays
Question:
Can a function be stored in a PHP array?
Answer:
Yes, it is possible to store a function in a PHP array. There are several approaches to do this:
<code class="php">$functions = [ 'function1' => function ($echo) { echo $echo; } ];</code>
<code class="php">function do_echo($echo) { echo $echo; } $functions = [ 'function1' => 'do_echo' ];</code>
<code class="php">$functions = [ 'function1' => create_function('$echo', 'echo $echo;') ];<p>Once stored in an array, the function can be called directly or via call_user_func:</p> <pre class="brush:php;toolbar:false"><code class="php">$functions['function1']('Hello world!'); call_user_func($functions['function1'], 'Hello world!');</code>
Best Alternative:
The recommended alternative is using anonymous functions, as it provides a concise and standardized way to store functions in arrays, especially in PHP versions 5.3 and above.
The above is the detailed content of Can Functions be Stored in PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!