Home >Backend Development >PHP Tutorial >How Do You Store and Call Functions Within PHP Arrays?

How Do You Store and Call Functions Within PHP Arrays?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 13:56:29715browse

How Do You Store and Call Functions Within PHP Arrays?

Storing Functions in PHP Arrays

In PHP, it is possible to store functions within arrays. This can be beneficial for organizing and accessing functions dynamically in your code.

Anonymous Functions

The recommended approach is to use anonymous functions, which can be stored directly in arrays. An anonymous function is created using this syntax:

function ($args) {
  // Function body
}

For example:

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

Pre-Declared Functions

If you want to store a function that has already been declared, you can simply refer to it by name as a string:

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

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

Using create_function

In older versions of PHP (before 5.3), anonymous functions were not supported. In such cases, you can use the deprecated create_function function:

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

Accessing and Calling Stored Functions

Once functions are stored in an array, they can be called either directly (PHP >= 5.4) or using call_user_func or call_user_func_array functions:

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

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

Conclusion

The ability to store functions in PHP arrays provides flexibility and organization in code. Anonymous functions, pre-declared function references, and create_function (deprecated) offer different ways to achieve this.

The above is the detailed content of How Do You Store and Call Functions Within 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