Self Executing functions in PHP5.3?

后端 未结 1 1273
生来不讨喜
生来不讨喜 2020-12-24 11:46

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\';
})();
相关标签:
1条回答
  • 2020-12-24 12:17

    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
    
    0 讨论(0)
提交回复
热议问题