6

Why would PHP allow nesting functions?

<?php
function foo() {
    function bar() {
        return "bar";
    }
    return "foo";
}
print foo();
print bar();

.. is valid PHP.

But:

  1. Why would nesting be needed ever?
  2. And even if so, why can I call bar from anywhere (and not, e.g. only withing foo(), or trough foo.bar() or such).

I ran into this today, because I forgot a closing bracket somewhere, and had one too many further down. The code was valid and no errors thrown; but it all started acting really weird. Functions not being declared, callbacks going berserk and so on. Is this a feature, and if so, to what purpose? Or some idiosyncrasy?

ANSWER: commentor points out that this is a duplicate of What are php nested functions for.

Community
  • 1
  • 1
berkes
  • 26,996
  • 27
  • 115
  • 206

2 Answers2

7

Note that the order is important here; you cannot call bar() before calling foo() in your example. The logic here appears to be that the execution of foo() defines bar() and puts it in global scope, but it's not defined prior to the execution of foo(), because of the scoping.

The use here would be a primitive form of function overloading; you can have your bar() function perform different operations depending upon which version of foo() declares it, assuming of course that each different version of foo() indeed defines a bar() function.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
  • 2
    I wonder what happens when `foo()` is called a second time. One would think an error would be thrown because `bar()` is already defined. – dnagirl Nov 15 '10 at 17:37
6

In PHP you can define functions, run-time constants and even classes conditionally. This allows you to define different functions / constants / classes depending on the circumstances.

Simply example: Define the String\Length function depending on whether multibyte support is turned on or off in your application.

namespace String;

if (\MULTIBYTE_MODE) {
    function Length($string) {
        return strlen($string);
    }
} else {
    function Length($string) {
        return mb_strlen($string);
    }
}

Nested functions are only a special case of conditional function definition.

NikiC
  • 100,734
  • 37
  • 191
  • 225