【问题标题】:PHP __DIR__ evaluated runtime (late binding)?PHP __DIR__ 评估运行时(后期绑定)?
【发布时间】:2013-08-07 10:14:59
【问题描述】:

是否有可能在运行时评估 PHP 文件的位置?我正在寻找类似于魔术常数__DIR__ 的东西,但在运行时进行评估,作为后期绑定。与selfstatic类似的区别:

__DIR__ ~ self
  ???   ~ static

我的目标是在抽象类中定义一个方法,使用 __DIR__ 将分别为每个继承类评估。示例:

abstract class Parent {
  protected function getDir() {
    // return __DIR__; // does not work
    return <<I need this>>; // 
  }
}

class Heir extends Parent {
  public function doSomething() {
    $heirDirectory = $this->getDir();
    doStuff($heirDirectory);
  }
}

显然,只有ParentHeir 位于不同目录时才会出现此问题。请考虑到这一点。此外,在各种 Heir 类中一遍又一遍地定义 getDir 似乎不是一个选项,这就是我们有继承的原因......

【问题讨论】:

    标签: php inheritance dir late-binding


    【解决方案1】:

    您可以在Parent类的getDir方法中添加如下代码

    $reflector = new ReflectionClass(get_class($this));
    $filename = $reflector->getFileName();
    return dirname($filename);
    

    您的父类将如下所示

    abstract class Parent {
        protected function getDir() {
            $reflector = new ReflectionClass(get_class($this));
            $filename = $reflector->getFileName();
            return dirname($filename);
        }
    }
    

    希望它会有所帮助。

    【讨论】:

    • 这很酷......还有什么,人们?设计越简洁越好。
    • 也可以使用ReflectionObject:return dirname(new \ReflectionObject($this))-&gt;getFileName());
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 2019-04-02
    • 2011-04-20
    • 2019-05-30
    相关资源
    最近更新 更多