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.

3
  • For the sake of my curiosity, what's the advantage of declaring functions within methods? Commented Jan 20, 2011 at 13:58
  • @Gordon You have to call the function it's in first so that it will be defined. Commented Jan 20, 2011 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: php.net/manual/en/functions.anonymous.php Commented Jun 2, 2017 at 20:32

2 Answers 2

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.

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

3 Comments

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.
you may wish to update this to include information about namespaces now, as a new question has been pointed to this answer,
Are arrow function also global?
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

1 Comment

What does "by default" mean? How can I make a non-global function (apart from an anonymous function, which is a very different deal.)

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.