PHP 中的 IIFE(立即调用函数表达式)? [英] IIFE (Immediately Invoked Function Expression) in PHP?

查看:31
本文介绍了PHP 中的 IIFE(立即调用函数表达式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 PHP 是否有类似 Javascript 的 IIFE(立即调用函数表达式)的任何等价物.PHP Closure 是否可以以任何方式编写,以便它可以与 Javascript 类似地工作(调用、依赖、注入、指令)?

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', []);
}());

上面的这个表达式被称为立即调用函数表达式(IIFE).因为只要加载 .js 文件,函数定义就会立即调用自身.IIFE 有效的主要原因是我们可以立即执行所有代码,而无需全局变量和函数.现在,当我们这样做时,我们的控制器创建将失败,因为我们使用全局变量来创建带有模块的控制器.为了规避这个问题,让我们使用 getter 函数 angular.module 将控制器与模块相关联.当我们在做的时候,为什么不把控制器也放在一个 IIFE 中呢.

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

来源:http://www.codeproject.com/Articles/995498/Angular-Tutorial-Part-Understanding-Modules-and谢谢.

推荐答案

在 PHP 7 中,是的,您可以:

In PHP 7, yes, you can:

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

这在 PHP 5.x 中不起作用.相反,你能得到的最接近的是:

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

call_user_func(function() { echo "this works too\n"; });

这篇关于PHP 中的 IIFE(立即调用函数表达式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆