Search code examples
phpfileclass-design

Resolve a filename from another file


I can currently to the following:

class SubClass extends SuperClass {
  function __construct() {
    parent::__construct();
  }
}

class SuperClass {
  function __construct() {
    // this echoes "I'm SubClass and I'm extending SuperClass"
    echo 'I\'m '.get_class($this).' and I\'m extending '.__CLASS__;
  }
}

I would like to do something similar with the filenames (__FILE__, but dynamically evaluated); I would like to know what file the subclass resides in, from the superclass. Is it possible in any elegant way?

I know you could do something with get_included_files(), but that's not very efficient, especially if I have numerous instances.


Solution

  • You can use Reflection.

    $ref = new ReflectionObject($this);
    $ref->getFileName(); // return the file where the object's class was declared