15

I have two classes in separate folders

class Parent { public $path = null; function __construct() { $this->path = __DIR__; } } 

and

class Child extends Parent { } 

So when I create an instance of Child:

$child = new Child(); echo $child->path 

I get a path to Parent. What I actually want is to get path to Child. I cannot modify Child class.

Is it possible?

3
  • 1
    Don't think this can be done. Why do you need to know the directory of the child? Why can't you modify it? Commented Oct 9, 2010 at 7:30
  • tandu, I cannot modify Childs, cause they are added as extensions by users. And it would be bad to force users to add this DIR thing into every class they create. Parent here represents basic functionality needed by core program so it can autoload resources stored in Child's directory. So core program autoloads all user defined Childs and loads associated resources automatically. Commented Oct 9, 2010 at 7:50
  • Possible duplicate of PHP __DIR__ evaluated runtime (late binding)? Commented Jun 6, 2016 at 3:47

1 Answer 1

32

You can get use reflection to get what you're looking for:

$child = new Child(); $class_info = new ReflectionClass($child); echo dirname($class_info->getFileName()); 
Sign up to request clarification or add additional context in comments.

4 Comments

If that works, please mark the answer as accepted by clicking the checkbox. That will remove this from the "unanswered questions" list.
I already did that, but it seems that yesterday glitch at stackoverflow rolled it back..
Check this out: $class_info = new ReflectionClass($this);
Keep in mind that Reflection should not be used in production because it is slow as hell.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.