Okay, so this has been baking my noodle for a little while now. I have a class with a method that defines a globally accessible function. My question is: how is it possible for an internal class method to define a function that is accessible at the global scope?
Here’s a sample:
class MyClass
{
// ... accessors, constuctors other methods, et al...
// The method in question:
private function myPrivateMethod()
{
if( !function_exists( 'someArbitraryFunction' ) )
{
function someArbitraryFunction( $args )
{
return "Hello, {$args} world!";
}
}
}
}
The class is instantiated as usual, and very early on in the application, but it is instantiated within another class’s method. It’s a shallow scope-chain, but nested enough that it doesn’t make sense (to me) why it would be accessible outside of the application. This goes against my understanding of encapsulation, some insight would be much appreciated.
Functions declared will always have a global scope. This is not JavaScript.
See:
Being a language from a C/C++ background, there is a distinct behaviour between functions and methods. In PHP, functions do not obey the access modifiers.
Regardless of where they are written in the code, once the execution runs through the declaration, it becomes defined.
If you need a function to obey scoping, which I highly recommend because you get to utilize the GC of variables better, you can use Closures in >= PHP 5.3: