How to get the path of the current class, from an inherited method?
I have the following:
Yes. Building on Palantir's answer:
class Parent {
protected function getDir() {
$rc = new ReflectionClass(get_class($this));
return dirname($rc->getFileName());
}
}
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);
<?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__
.
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() :)
You can also pass the directory as constructor arg. Not super elegant, but at least you don't have to work with reflection or composer.
Parent:
<?php // file: /parentDir/class.php
class Parent {
private $directory;
public function __construct($directory) {
$this->directory = $directory;
}
protected function getDir() {
return $this->directory;
}
}
?>
Child:
<?php // file: /childDir/class.php
class Child extends Parent {
public function __construct() {
parent::__construct(realpath(__DIR__));
echo $this->getDir();
}
}
?>
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());
}