views:

143

answers:

4

I know that it is possible to create a function within another function. Why might one need to do that in real life? (PHP)

function someFunction($var)  
{  
    function anotherFunction()
    {
        return M_PI;
    }

    return anotherFunction();
}
A: 

Because, sometimes the "outer" function will want to call an "inner" function to possibly reduce code redundancy or simplify steps. However, if this code is not something that would be globally use (outside the "outer" function) then you may want to make it so it can only be called within that function.

Matt
but once the outer function is called once, the inner function becomes global. :/ and also, wouldnt it be simpler if we defined the function outside. I mean steps are more if we have a function inside another function. and it also complicates things.
Shafee
You could always just make an anonymous function to do this...
Chacha102
+4  A: 

The only time you'd ever really want to define a function inside of another function is if you didn't want that inner function available to anything until the outer function is called.

function load_my_library() {
  ...

  function unload_my_library() {
  }
}

The only time you'd need (or want) unload_my_library to be available is after the library has been loaded.

Cryo
+1 I would see this as a logical extension of creating functions conditionally, i.e. `if (...) { function foo() { ... } }`. Nesting this inside another function instead of an `if` may come in handy for code organization purposes. "Conditional functions" are handy in certain cases, one of the most used being the retrofitting of necessary functions into old PHP versions.
deceze
+1  A: 

Nested functions generally shouldn't ever be used. Classes and public/private methods solve the same sorts of problems much more cleanly.

However, function generating functions can be useful:

<?php
# requires php 5.3+
function make_adder($a)
{
  return function($b) use($a) {
    return $a + $b;
  };
}

$plus_one = make_adder(1);
$plus_fortytwo = make_adder(42);

echo $plus_one(3)."\n";       // 4
echo $plus_fortytwo(10)."\n"; // 52

?>

This example is contrived and silly, but this sort of thing can be useful for generating functions used by sorting routines, etc.

konforce
A: 

I'm guessing here, but I believe that it is used for passing the function to another function for execution. For example, calling a search function where you can specify a callback function to perform the search order comparison. This will allow you to encapsulate the comparator in your outer function.

Toybuilder