0

I recently came across the magic constant __DIR__ when resolving an issue regarding including scripts within included scripts.

After doing some reading I couldn't find any reason not to use __DIR__ to prefix every path in a require or include statement.

So my questions is - are there any known downsides / potential side effects to be aware of when using __DIR__ . '/path/to/script.php' compared to using relative paths?

Thanks.

gnusey
  • 354
  • 3
  • 16
  • 6
    No downsides when using `__DIR__` – DarkBee Jan 26 '18 at 10:51
  • Given that autoloaders are more or less ubiquitous now, how many times are you finding yourself including files manually? – iainn Jan 26 '18 at 10:55
  • 1
    He seems to be new to this topic, asking such question. It's supposable that he don't know about autoloading yet, or don't really use it by now. So generally, his question is completely fine. And beside the autoloading, he will be came across things like `__DIR__` over and over again in his lifetime. ;) @iainn – eisbehr Jan 26 '18 at 11:01

1 Answers1

3

PHP has two modes of including files: based on relative paths, and based on absolute paths:

require 'foo/bar.php';
require '/var/www/foo/bar.php';

When using relative paths, the lookup is performed based on the PHP include path, which is basically a list of directories PHP will look up stuff in similar to the UNIX $PATH environment variable. Iif you're using PEAR or other module installers which install PHP modules and files in some external directories, then it makes perfect sense to use that mechanism to locate and include external modules. You might even use that mechanism for files inside your own app. It gives you more leeway when deploying apps on a server in deciding on the exact file placement.

However, in practice this somehow turned out to be rather annoying and you'll run into all sorts of issues when trying to use that system. Not least of all because PEAR and PECL didn't turn out to be particularly popular, and composer is the de-facto mechanism to manage dependencies in PHP these days. So the include-by-relative-path mechanism is all but dead and you should be using absolute paths, for which __DIR__ is kind of a must really.

deceze
  • 510,633
  • 85
  • 743
  • 889