0

Possible Duplicate:
Anonymous functions that execute immediately

javascript code:

(function(){
  var msg = 'Hello World';
  console.log(msg);
})();

Is there an equivalent way to do this in php?

Community
  • 1
  • 1
Eran Or
  • 1,252
  • 15
  • 22
  • Self Executing functions in PHP5.3? http://stackoverflow.com/questions/3865934/self-executing-functions-in-php5-3 – Mustafa Shujaie Jan 19 '13 at 21:20
  • Maybe the anonymous functions is what are looking for: http://php.net/manual/en/functions.anonymous.php – Muatik Jan 19 '13 at 21:21
  • Not sure what yet are trying to accomplish. Can you reword the question – Hydra IO Jan 19 '13 at 21:22
  • 2
    What's your intention? In JS it is usually done for scoping or creating new variables to work around issues with closures. Is that what you intend to do in your PHP code, too? – ThiefMaster Jan 19 '13 at 21:22
  • as @gordon says in http://stackoverflow.com/questions/3865934/self-executing-functions-in-php5-3 Function Call Chaining, e.g. foo()() is in discussion for PHP5.4. Until then, use call_user_func: – Mustafa Shujaie Jan 19 '13 at 21:23
  • and here: "Anonymous functions that execute immediately" http://stackoverflow.com/questions/3568410/anonymous-functions-that-execute-immediately – Mustafa Shujaie Jan 19 '13 at 21:25

2 Answers2

0

The pattern in your example is used to overcome issues with function-level static scoping in javascript. There is no equivalent pattern in PHP, since PHP has no such issues.

You might as well just create a new class.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
0

It is possible:

call_user_func(function() {
  $localvar = 'foo';
  echo $localvar;
});

And while I agree that it has less value in PHP than in JS, there are use cases, i.e. procedural include files. For further description of the method, see my blog.

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111