views:

104

answers:

2

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.

A: 

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
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
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
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
Oh, and they all need to be uniquely identified upon initialization...
Henrik Paul
+1  A: 

You can use Reflection.

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