1

If I pass an anonymous function as an argument, how is it instantiated?

Example: thing(function(){ ... });

In particular, I am wondering whether the anonymous function is attached to the scope of the caller, or the internal scope of the function, or the global scope - i.e. is the garbage collector able to clear it?

For instance, will this run out of memory: while(true) { thing(function(){ ... }); }

Benubird
  • 18,551
  • 27
  • 90
  • 141
  • 1
    [This answer](http://stackoverflow.com/a/6297966/1945960) is pretty good on this matter and specially on explaining how you can end up with unwanted references to the anonymous function when closures are involved. – HiDeoo Aug 23 '16 at 08:09
  • @HiDeo That is a good answer and helpful, although it is about javascript rather than PHP, so it's possible the php gc might work differently. – Benubird Aug 23 '16 at 08:37
  • My bad, was pretty sure I saw the javascript tag and indeed you should not take this bad comment into consideration. I need coffee. – HiDeoo Aug 23 '16 at 08:41
  • 1
    In addition to the linked question: There are two parts to the closure: The compiled function and the closure object referencing it. The former will stay around for the whole request just like any function, while the latter is garbage collected as usual. The difference to create_function is that there is only a *single* global compiled function per closure which is referenced by the individual closure objects. For create_function on the other hand each call will create a new compiled function. – NikiC Sep 03 '16 at 12:58

0 Answers0