How to get the path of a derived class from an inherited method?
Solution 1
Using ReflectionClass::getFileName
with this will get you the dirname the class Child
is defined on.
$reflector = new ReflectionClass("Child");
$fn = $reflector->getFileName();
return dirname($fn);
You can get the class name of an object with get_class()
:)
Solution 2
Yes. Building on Palantir's answer:
class Parent {
protected function getDir() {
$rc = new ReflectionClass(get_class($this));
return dirname($rc->getFileName());
}
}
Solution 3
Don't forget, since 5.5 you can use class
keyword for the class name resolution, which would be a lot faster than calling get_class($this)
. The accepted solution would look like this:
protected function getDir() {
return dirname((new ReflectionClass(static::class))->getFileName());
}
Solution 4
If you are using Composer for autoloading you can retrieve the directory without reflection.
$autoloader = require 'project_root/vendor/autoload.php';
// Use get_called_class() for PHP 5.3 and 5.4
$file = $autoloader->findFile(static::class);
$directory = dirname($file);
Solution 5
<?php // file: /parentDir/class.php
class Parent {
const FILE = __FILE__;
protected function getDir() {
return dirname($this::FILE);
}
}
?>
<?php // file: /childDir/class.php
class Child extends Parent {
const FILE = __FILE__;
public function __construct() {
echo $this->getDir();
}
}
$tmp = new Child(); // output: '/childDir'
?>
Please not that if you need to get the dir, directly use __DIR__
.
Related videos on Youtube
Comments
-
Jacco over 3 years
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()); } } ?>
-
Dan Johnson over 7 yearsMate, I have spent about 4 hours today searching for a way to do this without using Reflection!! Thanks!
-
coccoinomane over 2 yearsThanks! If you are using namespaces, make sure to change
new ReflectionClass(...)
withnew \ReflectionClass(...)
.