17

I was wondering why php handles the scope of a declared function within a function differently when a function is declared inside a class function.

For example:

function test() // global function
{
  function myTest() // global function. Why?
  {
    print( "Hello world" );
  } 
}

class CMyTestClass
{
  public function test() // method of CMyTestClass
  {
    function myTest() // This declaration will be global! Why?
    {
      print( "Hello world" );
    } 
  }
}

}

Can anybody explain this to me why this happen? Thank you for your answer.

Greetz.

Codebeat
  • 6,501
  • 6
  • 57
  • 99
  • For the sake of my curiosity, what's the advantage of declaring functions within methods? – Mike B Jan 20 '11 at 13:58
  • @Gordon You have to call the function it's in first so that it will be defined. – Wiseguy Jan 20 '11 at 14:06
  • @MikeB - Perhaps there are other reasons, but this approach could be an attempt at a sort of "anonymous function". The correct format for doing so is here: http://php.net/manual/en/functions.anonymous.php – rinogo Jun 02 '17 at 20:32

2 Answers2

12

In PHP all functions are always global, no matter how or when you define them. (Anonymous functions are partially an exception to this.) Both your function definitions will thus be global.

From the documentation:

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

NikiC
  • 100,734
  • 37
  • 191
  • 225
  • 4
    To add to this answer, the linked documentation also says this: "Functions need not be defined before they are referenced, except when a function is conditionally defined ... Its definition must be processed prior to being called." Thus, the function that the definition is within must be called first for it to be defined. – Wiseguy Jan 20 '11 at 14:13
  • 1
    you may wish to update this to include information about namespaces now, as a new question has been pointed to this answer, – Barkermn01 Dec 16 '21 at 00:44
  • Are arrow function also global? – theking2 Mar 16 '23 at 18:47
6

When you define a function within another function it does not exist until the parent function is executed. Once the parent function has been executed, the nested function is defined and as with any function, accessible from anywhere within the current document. If you have nested functions in your code, you can only execute the outer function once. Repeated calls will try to redeclare the inner functions, which will generate an error.

Now all php functions are global by default. So your nested function becomes global the second you call the outer function

o0'.
  • 11,739
  • 19
  • 60
  • 87
ayush
  • 14,350
  • 11
  • 53
  • 100
  • 2
    What does "by default" mean? How can I make a non-global function (apart from an anonymous function, which is a very different deal.) – NikiC Jan 20 '11 at 14:09