IIFE (Immediately Invoked Function Expression) in PHP?

Posted on

IIFE (Immediately Invoked Function Expression) in PHP? – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like javascript and php . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about IIFE (Immediately Invoked Function Expression) in PHP?.

I wonder if PHP has any equivalence of IIFE (Immediately Invoked Function Expression) like that of Javascript. Can PHP Closure be written anyhow so it can work similarly to Javascript (invoking, dependency, injection, directive) ?

    myModule = angular.module('myAngularApplication', []);

This expression above is known as Immediately invoked function expression(IIFE). Since the function definition will immediately invoke itself whenever the .js file is loaded. The main reason the IIFE is effective is that we can have all the code immediately executing without needing to have global variables and functions. Now when we do this, our controller creation will fail as we were using the global variable to create controller with the module. To circumvent this problem lets use the getter function angular.module to associate the controller with the module. And while we are at it, why not put the controller in an IIFE too.

(function () {

    var booksController = function ($scope) {
         $scope.message = "Hello from booksController";

    angular.module('myAngularApplication').controller('booksController', booksController); 

Source: http://www.codeproject.com/Articles/995498/Angular-Tutorial-Part-Understanding-Modules-and
Thank you.

Solution :

In PHP 7, yes, you can:

(function() { echo "yes, this works in PHP 7.n"; })();

This does not work in PHP 5.x. Instead, the closest you can come is:

call_user_func(function() { echo "this works toon"; });

Leave a Reply

Your email address will not be published. Required fields are marked *