PHP Nested classes work… sort of?

后端 未结 3 1877
死守一世寂寞
死守一世寂寞 2020-12-10 06:21

So, if you try to do a nested class like this:

//nestedtest.php

class nestedTest{
    function test(){
         class E extends Exception{}
         throw n         


        
相关标签:
3条回答
  • 2020-12-10 06:54

    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.

    0 讨论(0)
  • 2020-12-10 07:02

    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.

    0 讨论(0)
  • 2020-12-10 07:13

    There's no good reason to define a class inside a method. The 2nd way "works" only in the sense that it doesn't throw an error - the class still exists in the same scope/namespace as all the other defined classes. So, you're not actually "nesting" a class in this scenario.

    By the way, the reason it works is because a class is merely a definition - there is no execution involved with defining a class. So that file (e.php) is parsed as soon as you include it, and then its class becomes available to the current execution context. Only the executable portions of the code (i.e., throw new E;) will actually belong to the scope of the caller.

    0 讨论(0)
提交回复
热议问题