Home  >  Article  >  Backend Development  >  Can Functions be Stored in PHP Arrays?

Can Functions be Stored in PHP Arrays?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 06:38:30857browse

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:

  • Anonymous Function:
<code class="php">$functions = [
  'function1' => function ($echo) {
    echo $echo;
  }
];</code>
  • String Reference to an Existing Function:
<code class="php">function do_echo($echo) {
  echo $echo;
}

$functions = [
  'function1' => 'do_echo'
];</code>
  • Deprecated create_function Method (PHP < 5.3):
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn