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?
__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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With