How Do You Store Functions in an Array in PHP?

Susan Sarandon
Release: 2024-11-02 16:33:03
Original
610 people have browsed it

How Do You Store Functions in an Array in PHP?

Exploring Array Storage of Functions in PHP

PHP offers several options for storing functions in arrays, each with its own implications.

Anonymous Functions

The preferred approach is to use anonymous functions:

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

Anonymous functions allow you to define a function on-the-fly, without declaring it beforehand.

Referencing Named Functions

If you want to store an existing function, you can reference it by name as a string:

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

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

This method involves declaring the function outside of the array.

Legacy Approach (PHP < 5.3)

For older versions of PHP that do not support anonymous functions, you can use create_function:

<code class="php">$functions = array(
  'function1' => create_function('$echo', 'echo $echo;')
);<p>However, this approach is deprecated and should be avoided if possible.</p>
<p><strong>Invoking Stored Functions</strong></p>
<p>Regardless of the storage method used, you can invoke the functions directly (PHP >= 5.4) or with call_user_func/call_user_func_array:</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

The above is the detailed content of How Do You Store Functions in an Array in PHP?. 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