Self Executing functions in PHP5.3?

不羁岁月 提交于 2019-12-18 11:10:30

问题


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

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

right now I need to do:

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

It seems pointless...


回答1:


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

gives:

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

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

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


来源:https://stackoverflow.com/questions/3865934/self-executing-functions-in-php5-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!