Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Nested classes work... sort of?

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?

like image 365
SeanJA Avatar asked Apr 09 '10 14:04

SeanJA


2 Answers

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.

like image 81
Tom Haigh Avatar answered Sep 28 '22 19:09

Tom Haigh


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.

like image 22
Ivo Sabev Avatar answered Sep 28 '22 20:09

Ivo Sabev