Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ?

(function(){
    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.

like image 540
Pristine Kallio Avatar asked Jan 27 '16 17:01

Pristine Kallio


People also ask

What is an IIFE immediately invoked function expression )? Can you give an example?

An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.

What is the use of immediately invoked function expression?

An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.

What is IIFE immediately invoked function expression in JS?

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

Does declared function execute immediately?

Function expressions are evaluated during execution. So you can't execute function declarations immediately because even variables don't exist yet and other code that the function might depend on hasn't been executed either.


1 Answers

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 too\n"; });
like image 174
jbafford Avatar answered Oct 08 '22 22:10

jbafford