【问题标题】:How to open a .json file in a certain namespace如何在某个命名空间中打开 .json 文件
【发布时间】: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 );
  }
}

我找到的最接近的解决方案是在MyClassReflectionClass 中使用方法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


【解决方案1】:

您不能对 JSON 文件使用命名空间。但由于它与类在同一目录中,您应该可以使用__DIR__

<?php namespace Mynamespace\Subnamespace;

class MyClass {
  public function getFile() {
    $fileLocation = 'myfile.json';
    return file_get_contents( __DIR__ . PATH_SEPARATOR . $fileLocation );
  }
}

【讨论】:

  • 工作就像一个魅力。我错误地认为 DIR 会引用代码最初调用的路径,我错了!
【解决方案2】:

最简单的方法是使用get_class

<?php namespace Mynamespace\Subnamespace;

class MyClass {
  public function getFile() {
    // Will have backslashes so str_replace if this is a Unix environment
    $path = str_replace('\\', '/', get_class($this));
    $fileLocation = $path . '/myfile.json'; // Mynamespace/Subnamespace/myfile.json
    return file_get_contents( $fileLocation );
  }
}

【讨论】:

    【解决方案3】:

    如果我理解正确的话,就是这样:

    $fileLocation = __NAMESPACE__ . '\myfile.json';
    

    PHP: namespace keyword and __NAMESPACE__ constant

    但由于您声明“文件位于 Mynamespace\Subnamespace\file.json 中的此类旁边”,因此您可以只使用当前文件的完整路径:

    $fileLocation = __DIR__ . '\myfile.json';  // or  dirname(__FILE__)
    

    PHP: Magic Constants

    【讨论】:

      猜你喜欢
      • 2012-01-10
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      相关资源
      最近更新 更多