我有一个像这样的文件夹结构:
index.php
app/
controllers/
folder1/
class.php
class.php 中没有命名空间定义。是否可以将 class.php 放在从相对于索引的文件夹结构生成的命名空间中?所以它会像这样加载:
new \app\controllers\folder1\classInFile();
或者有没有办法动态创建命名空间?
最佳答案
A file containing a namespace must declare the namespace at the top of the file before any other code.
即,您不能在 namespace 声明之前执行任何代码,之后为时已晚。尽管有内省(introspection)的运行时黑客:不,这是不可能的。即使是这样,它也将取决于运行时信息,例如执行/包含代码的文件夹。命名空间可以是
var\www\myproject\foo\bar\baz
或只是 foo\bar\baz
.你将如何确定这一点?越来越乱了真的,只要让它明确,即使这意味着输入更多。命名空间是类名称的一部分。您不应在运行时动态生成名称。
关于PHP根据文件夹结构动态生成命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13510073/