What are PHP nested functions for?

meouw picture meouw · Jan 6, 2009 · Viewed 53.7k times · Source

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()

Answer

Gus picture Gus · May 20, 2011

If you are using PHP 5.3 you can get more Javacript-like behaviour with an anonymous function:

<?php
function outer() {
    $inner=function() {
        echo "test\n";
    };

    $inner();
}

outer();
outer();

inner(); //PHP Fatal error:  Call to undefined function inner()
$inner(); //PHP Fatal error:  Function name must be a string
?>

Output:

test
test