自执行函数在PHP5.3? [英] Self Executing functions in PHP5.3?

查看:80
本文介绍了自执行函数在PHP5.3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图借用一些程序范例从JS到PHP(只是为了乐趣)。
是否有办法:

I was trying to borrow some programing paradigms from JS to PHP (just for fun). Is there a way of doing:

$a = (function(){
  return 'a';
})();

我以为使用这可以是隐藏变量JS风格的好方法

I was thinking that with the combination of use this can be a nice way to hide variables JS style

$a = (function(){
    $hidden = 'a';
    return function($new) use (&$hidden){
        $hidden = $new;
        return $hidden;
    };
})();

现在我需要:

$temp = function(){....};
$a = $temp();

似乎毫无意义...

推荐答案

函数调用链 foo()正在讨论PHP5.4。在此之前,使用 call_user_func

Function Call Chaining, e.g. foo()() is in discussion for PHP5.4. Until then, use call_user_func:

$a = call_user_func(function(){
    $hidden = 'a';
    return function($new) use (&$hidden){
        $hidden = $new;
        return $hidden;
    };
});

$a('foo');    
var_dump($a);

给出:

object(Closure)#2 (2) {
  ["static"]=>
  array(1) {
    ["hidden"]=>
    string(3) "foo"
  }
  ["parameter"]=>
  array(1) {
    ["$new"]=>
    string(10) "<required>"
  }
}


$ b $ p从PHP7开始,您可以立即执行匿名函数this:

As of PHP7, you can immediately execute anonymous functions like this:

(function() { echo 123; })(); // will print 123

这篇关于自执行函数在PHP5.3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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