Nested Functions in PHP (original) (raw)

NOTICE: This content is in the "archives" of a retired blog called Gadgetopia. It has been moved to this subdomain as it is no longer considered relevant to the site. It is being hosted here for a indeterminate period of time. Its existence at this URL is not guaranteed, and it may be removed at any time. If you would like to refer to this content in the future, you are encouraged to save it to your local file system.

Some content from Gadgetopia was moved to the technical blog on deanebarker.net


[PHP: Advanced Functions](http://academ.hvcc.edu/\~kantopet/php/index.php?page=php adv functions&parent=php flow control “PHP: Advanced Functions”): I stumbled in this phenomenon today by accident. I was going nuts trying to find a bug until I realized I had declared a function inside another function. I couldn’t figure out why the parser didn’t fail…when I realized that what I did is completely legal.

When you define a function within another function it does not exist until the parent function is executed. Once the parent function has been executed, the nested function is defined and as with any function, accessible from anywhere within the current document. If you have nested functions in your code, you can only execute the outer function once. Repeated calls will try to redeclare the inner functions, which will generate an error.

Can someone please explain why you’d need this? I know there has to be a reason, but I can’t for the life me figure out what it is.

If the inner function stayed local, that would be one thing. But it becomes global the second you call the outer function, so why not just make it global from the beginning? Is it to save memory by not declaring a bunch of functions until you need them? Has anyone ever done this?