开发者

__DIR__ VS using Reflection

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 differe开发者_Go百科nce between them?


__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.


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.


__DIR__ exists only in PHP 5.3. Before 5.3, we had to use dirname(__FILE__) or something similar.


I think it is because __DIR__ will return the directory of the script that was initially invoked. In the code example, you would get the directory of the object's class. I may be wrong though have not tried this yet please correct me anyone if I am.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜