Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__DIR__ VS using Reflection

Tags:

php

symfony

In Symfony2, I saw the code like below:

    if (null === $this->rootDir) {
        $r = new \ReflectionObject($this);
        $this->rootDir = dirname($r->getFileName());
    }

why not just use the __DIR__?

    if (null === $this->rootDir) {
        $this->rootDir = __DIR__;
    }

What is difference between them?

like image 845
xdazz Avatar asked Aug 13 '26 07:08

xdazz


2 Answers

__DIR__ returns the directory of the file where it is called. The Symphony2 code returns the directory of where the class is defined, which most likely is a different file.

like image 188
Sander Marechal Avatar answered Aug 16 '26 12:08

Sander Marechal


As PHP manual states:

  • DIR returns the directory of the file. If used inside an include, the directory of the included file is returned
  • FILE returns the full path and filename of the file. If used inside an include, the name of the included file is returned.

So these constants always returns paths of the file where there are used. However, I suppose that it is not the expected behaviour in the code snippet you cited. Possibly the code resides in some base class, while it can be invoked from extending classes. If we want to get the path to the current class, the first way is the correct one.

like image 41
Karén Nalbandian Avatar answered Aug 16 '26 13:08

Karén Nalbandian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!