问题
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