PHP中被include的文件是否继承父文件的namespace?
PHP引入文件不会继承父文件的命名空间
被引入的anotherFile.php不会继承index.php中声明的testing命名空间。
在PHP中,命名空间的作用域是基于单个文件独立存在的,每个PHP文件的命名空间需要自行显式声明:
- 如果
anotherFile.php没有主动声明namespace testing;,它的代码默认处于全局命名空间(无命名空间状态)。 - 只有当
anotherFile.php自身显式添加namespace testing;声明时,它的代码才会归属到testing命名空间下。
举个实际例子:
- 未声明命名空间的
anotherFile.php:
// anotherFile.php // 代码默认属于全局命名空间 class TestClass {}
此时在index.php中调用这个类,必须使用全局空间的语法(前缀加反斜杠):
// index.php namespace testing; include __DIR__ . '/anotherFile.php'; // 调用全局空间的类,需加反斜杠前缀 $obj = new \TestClass();
- 显式声明命名空间的
anotherFile.php:
// anotherFile.php namespace testing; class TestClass {}
这时在index.php中可以直接调用该类:
// index.php namespace testing; include __DIR__ . '/anotherFile.php'; // 同命名空间下直接调用 $obj = new TestClass();
内容的提问来源于stack exchange,提问作者doqgmui
相关产品推荐
相关产品推荐

