So, if you try to do a nested class like this:
//nestedtest.php
class nestedTest{
function test(){
class E extends Exception{}
throw new E;
}
}
You will get an error Fatal error: Class declarations may not be nested in [...]
but if you have a class in a separate file like so:
//nestedtest2.php
class nestedTest2{
function test(){
include('e.php');
throw new E;
}
}
//e.php
class E Extends Exception{}
So, why does the second hacky way of doing it work, but the non-hacky way of doing it does not work?
From the manual (http://php.net/manual/en/function.include.php):
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
The second way is not nesting of classes. You just have your both declarations in one file, which is different from your first example. In PHP you can have multiple class declarations in one file it is a organizational decision not a requirement.
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