Scope of declared function within a function

2019-02-06 06:32发布

问题:

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.

回答1:

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.



回答2:

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