Can Functions be Stored in PHP Arrays?

Mary-Kate Olsen
Release: 2024-11-01 06:38:30
Original
854 people have browsed it

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>
Copy after login
  • String Reference to an Existing Function:
<code class="php">function do_echo($echo) {
  echo $echo;
}

$functions = [
  'function1' => 'do_echo'
];</code>
Copy after login
  • 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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!