2

Possible Duplicate:
What are PHP nested functions for?

PHP allows nested function declarations like so:

function foo() {
    function bar() {
        return "bar";
    }
    return "foo";
}

But what are the use cases for such a syntax? The inner bar is put to global namespace so so it's not garbage collected, is usable from outside the outer function and provides a lot of confusion and possible bugs. For example calling the foo twice results in an error, unless you wrap the declaration inside a if(!is_callable('bar')).

Using nested declarations to create conditional declarations is not good either, because of the confusion it creates. "Why is it complaining that there is no such function, when it works perfectly fine in there?!?!".

Community
  • 1
  • 1
Masse
  • 4,334
  • 3
  • 30
  • 41

1 Answers1

6

Well, conditional function declaration is probably the only legitimate use case, and there only to provide fallbacks for backwards compatibility:

function makeSureAllDependenciesExist() {
    if (!function_exists('someFunctionThatOnlyExistsInNewerPhpVersions')) {
        function someFunctionThatOnlyExistsInNewerPhpVersions() {
            // fallback implementation here
        }
    }
}

Other than that, there's indeed little reason to use nested function declarations.

deceze
  • 510,633
  • 85
  • 743
  • 889