What are PHP nested functions for?

If you are using PHP 5.3 you can get more JavaScript-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

Leave a Comment