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.
We can declare a function inside a function, but it's not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module.
Nested functions A function is called “nested” when it is created inside another function. It is easily possible to do this with JavaScript. Here the nested function getFullName() is made for convenience. It can access the outer variables and so can return the full name.
The scope of a variable is the region of your program in which it is defined. A global variable has global scope -- it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope.
No, it's not allowed. Neither C nor C++ support this feature by default, however TonyK points out (in the comments) that there are extensions to the GNU C compiler that enable this behavior in C.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With