How to get the path of the current class, from an inherited method?
I have the following:
<?php // file: /parentDir/class.php
class Parent {
protected function getDir() {
return dirname(__FILE__);
}
}
?>
and
<?php // file: /childDir/class.php
class Child extends Parent {
public function __construct() {
echo $this->getDir();
}
}
$tmp = new Child(); // output: '/parentDir'
?>
The __FILE__
constant always points to the source-file of the file it is in, regardless of inheritance.
I would like to get the name of the path for the derived class.
Is there any elegant way of doing this?
I could do something along the lines of $this->getDir(__FILE__);
but that would mean that I have to repeat myself quite often. I'm looking for a method that puts all the logic in the parent class, if possible.
Update:
Accepted solution (by Palantir):
<?php // file: /parentDir/class.php
class Parent {
protected function getDir() {
$reflector = new ReflectionClass(get_class($this));
return dirname($reflector->getFileName());
}
}
?>