Home > Backend Development > PHP Tutorial > How to Store Functions in PHP Arrays?

How to Store Functions in PHP Arrays?

Susan Sarandon
Release: 2024-11-03 09:56:02
Original
604 people have browsed it

How to Store Functions in PHP Arrays?

Storing Functions in PHP Arrays

Storing functions in PHP arrays allows for more flexibility and dynamic code execution. However, the syntax provided in the question is outdated and not recommended.

Anonymous Functions

The most preferred method is to use anonymous functions:

<code class="php">$functions = [
  'function1' => function ($echo) {
        echo $echo;
   }
];</code>
Copy after login

Declared Function Names

If the function has already been declared, you can simply use its name as a string:

<code class="php">function do_echo($echo) {
    echo $echo;
}

$functions = [
  'function1' => 'do_echo'
];</code>
Copy after login

Pre-PHP 5.3

If using PHP versions prior to 5.3, you can resort to create_function():

<code class="php">$functions = array(
  'function1' => create_function('$echo', 'echo $echo;')
);</code>
Copy after login

Usage

Regardless of the method chosen, the functions can be called directly or using call_user_func() or call_user_func_array():

<code class="php">$functions['function1']('Hello world!');

call_user_func($functions['function1'], 'Hello world!');</code>
Copy after login

Note: For PHP versions less than 5.3, consider upgrading to a later version for improved functionality and security.

The above is the detailed content of How to Store Functions 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