Search code examples
phpnested-function

What are PHP nested functions for?


In JavaScript nested functions are very useful: closures, private methods and what have you..

What are nested PHP functions for? Does anyone use them and what for?

Here's a small investigation I did

<?php
function outer( $msg ) {
    function inner( $msg ) {
        echo 'inner: '.$msg.' ';
    }
    echo 'outer: '.$msg.' ';
    inner( $msg );
}

inner( 'test1' );  // Fatal error:  Call to undefined function inner()
outer( 'test2' );  // outer: test2 inner: test2
inner( 'test3' );  // inner: test3
outer( 'test4' );  // Fatal error:  Cannot redeclare inner()

Solution

  • There is none basically. I've always treated this as a side effect of the parser.

    Eran Galperin is mistaken in thinking that these functions are somehow private. They are simply undeclared until outer() is run. They are also not privately scoped; they do pollute the global scope, albeit delayed. And as a callback, the outer callback could still only be called once. I still don't see how it's helpful to apply it on an array, which very likely calls the alias more than once.

    The only 'real world' example I could dig up is this, which can only run once, and could be rewritten cleaner, IMO.

    The only use I can think of, is for modules to call a [name]_include method, which sets several nested methods in the global space, combined with

    if (!function_exists ('somefunc')) {
      function somefunc() { }
    }
    

    checks.

    PHP's OOP would obviously be a better choice :)