Home >Backend Development >PHP Tutorial >How can I achieve Immediately Invoked Function Expressions (IIFE) in PHP?

How can I achieve Immediately Invoked Function Expressions (IIFE) in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 11:10:02681browse

How can I achieve Immediately Invoked Function Expressions (IIFE) in PHP?

PHP's Immediate Function Invocation

In PHP, the Immediately Invoked Function Expression (IIFE) has a partial equivalence in PHP 7, as you can invoke a function immediately after its definition. However, PHP 5.x doesn't support this feature.

For PHP 7, an example would be:

<code class="php">(function() { echo "yes, this works in PHP 7.\n"; })();</code>

For PHP 5.x, the closest approximation is:

<code class="php">call_user_func(function() { echo "this works too\n"; });</code>

This usage allows you to execute code immediately without the need for global variables and functions, making it convenient for encapsulation and dependency injection.

The above is the detailed content of How can I achieve Immediately Invoked Function Expressions (IIFE) in PHP?. 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