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?