IIFE (Immediately Invoked Function Expression) in PHP?
Asked Answered
H

2

25

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.

Hoban answered 27/1, 2016 at 17:44 Comment(9)
php code doesn't place the same priority on global-avoidance that JS does, for a host of reasons.Prochoras
The anonymous IIFE pattern in JS is to provide some semblance of private variables (since ES5 variables were function-scope only). The pattern expands to function foo() {...}; foo(); which can be done in any language.Tenpenny
except that your IIFE does create a global variable. O.oEngrain
Possible duplicate of Creating and invoking an anonymous function in a single statementExecratory
You can always namespace your code so you don't pollute the global namespace.Drawbar
@Prochoras yes, every time writing PHP code, I have to make sure no duplication in naming convention by using prefixes $t_my_var for temporary, $g_my_var for global, scoping with private and enclosing with class MySuperClosure{ } to avoid duplication.Hoban
Have you thought about reconsidering your design instead of trying to force JS' broken (yeah yeah I know) scoping solutions into your php projects?Fraase
@Prochoras why doesn't PHP put the same priority on global-avoidance? (new to PHP from JS, so I really don't know)Hicks
@Scribblemacher:speculation, but it's typically (non fpm) short-lived (less chances of hard-to-debug conflicts), it has a ton of its own globals compared to js (tradition, less reliance on hastily-written helper methods), and it tends to use a lot less 3rd party code (code that assumes a squeaky clean environ).Prochoras
L
55

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"; });
Loxodrome answered 27/1, 2016 at 17:49 Comment(3)
Oh, that would be nice but my IDE provider on the cloud still services PHP at 5.5.9.Hoban
It prevents accidental use of globals, so yes, it is often a good idea--though PHP's formal namespace mechanism may minimize the need.Pension
Another option is to define it into a variable - this is useful if you need to call it multiple times, e.g. $func = function($param) { echo $param; }; $func('Hello');Neale
G
2

You can also immediately invoke annonymous class in php.

<?php new class (0,1) {
  public function __construct (int $a, int $b) {

    (($a < 1) ? 'var_dump' : 'var_export')(
      gettype (($b > 0) ? __FUNCTION__ 
        : (($a > 0) ? microtime (true) 
        : __LINE__
    )))&exit;
    
  }
};
Guenon answered 9/10, 2022 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.