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

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

问题描述

我想知道PHP是否像Javascript一样具有IIFE(立即调用函数表达式)的等价. 可以以任何方式编写PHP闭包,使其可以类似于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-理解模块和 谢谢.

推荐答案

在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天全站免登陆