36

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...

4
  • 1
    hard to understand for me... :) what exactly you meant.. Commented Oct 5, 2010 at 17:02
  • I'm a little confused what you're trying to accomplish or why you want to execute functions this way. Although I'm pretty sure there is no way to encapsulate a function like that in PHP. Functions in javascript are implemented as classes, whereas in PHP they are actual functions. For this reason they all exist within a global namespace, not within their self-contained namespace. The closest thing to a "self-calling function" I could imagine would be to define the function within eval() Commented Oct 5, 2010 at 17:03
  • XiroX: would you perhaps consider asking a question? Commented Oct 5, 2010 at 18:01
  • 3
    PHP5.3 have lambda support, and so I wanted to know if there was a way of invoking them without assigning them to a variable. Commented Oct 6, 2010 at 13:28

1 Answer 1

68

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
Sign up to request clarification or add additional context in comments.

3 Comments

Would you possibly be able to update this? Would be appreciated.
Terrific, I have no doubt this will be a value to the community and future googlers.
FYI, function call chaining (which allows (function () {...})();) does not work in PHP 5.6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.