9

Let's say I have two files, each one has a class. How can I get the filename where the child class is, within the parent class?

File 2 (child class):

class B extends A{

}

File 1:

class A{

  final protected function __construct(){
    // here I want to get the filename where class B is, 
    // or whatever class is the child
  }

}
Alex
  • 66,732
  • 177
  • 439
  • 641
  • 2
    How are the classes instantiated with that protected constructor? – Phil Dec 03 '11 at 00:11
  • You want the parent class, to magically know the location of a single arbitrary child class somehow when it's constructed? That is not easily possible, and doesn't really have any purpose. What exactly are you trying to do? There's likely a better way to go about accomplishing your actual end goal. – Rylab Dec 03 '11 at 00:09

2 Answers2

19

Not really sure what purpose it serves, but here you go:

class A{

  final protected function __construct(){
    $obj = new ReflectionClass($this);
    $filename = $obj->getFileName();
  }

}
  • Wouldn't [ReflectionObject](http://php.net/manual/en/class.reflectionobject.php) be the right choice there? – Phil Dec 03 '11 at 00:15
  • You should change the constructor's accessibility to `public`. – webbiedave Dec 03 '11 at 00:16
  • 2
    @webbiedave It's hard to tell how the OP's creating objects with that protected constructor but they may have their reasons. Perhaps they have a public, static factory method on `A` – Phil Dec 03 '11 at 00:18
  • Well, Phil, I was just backing up your original comment on the OP's question and now you've bamboozled me! :) – webbiedave Dec 03 '11 at 00:23
4

You can cheat and use debug_backtrace:

class A {
  final protected function __construct() {
    $stacktrace = @debug_backtrace(false);
    $filename = $stacktrace[0]['file'];
  }
}
Ben Lee
  • 52,489
  • 13
  • 125
  • 145