简体   繁体   中英

Downsides to using __DIR__

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' __DIR__ . '/path/to/script.php' compared to using relative paths?

Thanks.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM