14

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?

ehpc
  • 1,034
  • 1
  • 9
  • 16
  • 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? – Explosion Pills Oct 09 '10 at 07: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. – ehpc Oct 09 '10 at 07:50
  • Possible duplicate of [PHP \_\_DIR\_\_ evaluated runtime (late binding)?](http://stackoverflow.com/questions/18100689/php-dir-evaluated-runtime-late-binding) – Marco Roy Jun 06 '16 at 03:47

1 Answers1

31

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());
bradym
  • 4,880
  • 1
  • 31
  • 36