1

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();
}
2
  • 1
    php.net/manual/en/language.functions.php#21150 Commented Feb 16, 2010 at 5:43
  • not that this answers why, but as in every language, there are features you just don't or shouldn't use. This one of those in my book. Commented Feb 16, 2010 at 6:04

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.