How to get the path of a derived class from an inherited method? How to get the path of a derived class from an inherited method? php php

How to get the path of a derived class from an inherited method?


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() :)


Yes. Building on Palantir's answer:

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


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