views:

1784

answers:

2

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()
+14  A: 

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

Eran Galperin is mistaken that these functions are somehow private, they are simply undeclared until outer() is run. They are also not privately scoped, they do polute the global scope albeit delayed. And as callback the outer callback could still only be called once. I still don't see how that's helpful applying it on an array which very likely calls the alias more then 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 :)

Martijn Laarman
Yes, you are right. I've edited my answer to reflect it
Eran Galperin
This is shocking.
rik.the.vik
Yeah, really. That's brutally bad.
Tony Arkles
+2  A: 

Functions defined within functions I can't see much use for but conditionally defined functions I can. For example:

if ($language == 'en') {
  function cmp($a, $b) { /* sort by English word order */ }
} else if ($language == 'de') {
  function cmp($a, $b) { /* sort by German word order; yes it's different */ }
} // etc

And then all your code needs to do is use the 'cmp' function in things like usort() calls so you don't litter language checks all over your code. Now I haven't done this but I can see arguments for doing it.

cletus
Back in the day, we would have called this self-modifying code. A great tool, but as dangerous as GOTO for abuse...
Killroy