0

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
Henrik Paul
  • 66,919
  • 31
  • 85
  • 96

2 Answers2

2

You can use Reflection.

$ref = new ReflectionObject($this);
$ref->getFileName(); // return the file where the object's class was declared
user27987
  • 219
  • 1
  • 3
0

Uh, not really, that I can think of. Each subclass would need to have an explicitly implemented method that returned __FILE__, which completely defeats the point of inheritance in the first place.

I'm also really curious as to why something like this would be useful.

Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • I'm creating a framework that should be able to tell apart two classes with the same names, and give them unique and consistent identifiers. Currently, I'm doing the pass-the-__FILE__-trick, and construct said identifier from the path. Namespaces could help, but they're a bit too new for my needs. – Henrik Paul Oct 14 '08 at 18:48
  • Now I'm really confused. Two classes with the same name? Won't you get a "Cannot redeclare class" error? Or are you actually planning on meta-programming each file? – Peter Bailey Oct 14 '08 at 19:52
  • They wouldn't normally be declared at the same time from PHP's point of view, as they would be in different modules, but in the same application. This isn't a normal case (and probably bad design), but I want it to be supported (because of 3rd party stuff - think CakePHP's bakery). – Henrik Paul Oct 15 '08 at 04:23