PHP嵌套类工作正常…… [英] PHP Nested classes work... sort of?

查看:138
本文介绍了PHP嵌套类工作正常……的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果您尝试做这样的嵌套类:

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

//nestedtest.php

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

您会收到错误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{}

那么,为什么第二种hacky方式有效,但是非hacky方式却无效?

So, why does the second hacky way of doing it work, but the non-hacky way of doing it does not work?

推荐答案

摘自手册( http://php.net/manual/zh/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.

这篇关于PHP嵌套类工作正常……的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆