简体   繁体   中英

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.

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"; });

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;
    
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM