PHP __DIR__ evaluated runtime (late binding)?

烈酒焚心 提交于 2019-12-09 06:07:40

问题


Is it somehow possible to get the location of PHP file, evaluated at runtime? I am seeking something similar to the magic constant __DIR__, but evaluated at runtime, as a late binding. Similar difference with self and static:

__DIR__ ~ self
  ???   ~ static

My goal is defining a method in an abstract class, using __DIR__ which would be evaluated respectively for each heir class. Example:

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);
  }
}

Obviously, this problem occurs only if Parent and Heir are in different directories. Please, take this into account. Also, defining getDir over and over again in various Heir classes does not seem to be and option, that's why we have inheritance...


回答1:


You can add the following code in getDir method of Parent class

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

Your parent class will look like this

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

Hoping it will help.



来源:https://stackoverflow.com/questions/18100689/php-dir-evaluated-runtime-late-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!