【发布时间】:2019-05-16 20:37:51
【问题描述】:
使用命名空间加载文件应该很容易,但我似乎无法生成它的 url。该文件位于与调用它的MyClass 相同的目录中。
<?php namespace Mynamespace\Subnamespace;
class MyClass {
public function getFile() {
$fileLocation = 'myfile.json'; // file is located next to this class in Mynamespace\Subnamespace\file.json
return file_get_contents( $fileLocation );
}
}
我找到的最接近的解决方案是在MyClass 的ReflectionClass 中使用方法getFileName()。但这会返回完整的 url,包括 MyClass.php 类文件。并且使用正则表达式似乎有点过头了,因为可能有更简单的解决方案。
如果可以以某种方式将命名空间转换为有效的 url,那应该可以解决问题。
file.json 应该如何获取?
【问题讨论】:
-
出于好奇,为什么不把这些写到一个中心位置呢?如果你这样做,维护起来会容易得多。
-
@AbraCadaver 是的,我尝试使用 NAMESPACE。这将返回命名空间的名称( Mynamespace\Subnamespace )。但是如果我生成像
Warning: file_get_contents(Mynamespace\Subnamespace\myfile.json): failed to open stream: No such file or directory..这样的命名空间,我的file_get_contents()函数会返回错误。所以显然我需要实际的 url 而不是命名空间。 -
JSON 文件的实际完整路径是什么?
-
@Machavity json 文件只存储了一些与
MyClass类特别相关的值。因此,将它们存储在一起似乎是个好主意。
标签: php namespaces