How can I store functions in PHP arrays effectively?

Linda Hamilton
Release: 2024-11-01 08:06:02
Original
938 people have browsed it

How can I store functions in PHP arrays effectively?

Storing Functions in PHP Arrays

The question arises whether it is possible to store functions within PHP arrays. For instance, consider the following:

$functions = [
  'function1' => function($echo) { echo $echo; }
];
Copy after login

Is this a viable approach? If not, what are the recommended alternatives?

Recommended Approach: Anonymous Functions

The preferred method for storing functions in arrays involves utilizing anonymous functions. Like the example above, they can be defined inline:

$functions = [
  'function1' => fn($echo) => $echo
];
Copy after login

Referencing External Functions

When dealing with pre-declared functions, you can reference them by name as strings:

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

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

Legacy Method (PHP < 5.3): create_function

For older versions of PHP that do not support anonymous functions, the create_function construct can be employed:

<code class="php">$functions = [
  'function1' => create_function('$echo', 'echo $echo;')
];<p><strong>Calling Stored Functions</strong></p>
<p>Regardless of the method used to store the function, it can be invoked directly (PHP >= 5.4) or through 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

In summary, anonymous functions are the recommended approach for storing functions in PHP arrays, with string references being used for pre-declared functions and create_function being available for legacy PHP versions.

The above is the detailed content of How can I store functions in PHP arrays effectively?. 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!