0

I've been hit by the issue in this question: PHP's path resolution for include, require, require_once, etc., was not what I expected.

The root cause of this issue is apparently that paths in all PHP files are resolved relative to the location of the script that was initially executed. However, I, like many others, expected the resolution to be relative to the location of the file that the include/require is included in.

The answers to the question I linked to explain that behavior, but do not address how to work around it. It seems to me that PHP's resolution method is inherently non-compositional: every file must be written with the assumption that it is included from a specific location, which breaks the compositional principle that modules are self-contained.

So, how do I work around this? Is there a "fixed" version of require_once which uses the resolution semantics that I and other people expect?

Community
  • 1
  • 1
jameshfisher
  • 34,029
  • 31
  • 121
  • 167
  • If you want to include something from the current directory (or starting at the current directory following any path), why don't you specify it this way, letting the path starting with `./`? Something like `./../f2/f2.inc.php` may seem odd, but is perfectly valid. – Ulrich Thomas Gabor Apr 03 '14 at 13:59
  • @GhostGambler I don't understand. Isn't `./../f2/f2.inc.php` equivalent to `../f2/f2.inc.php`? Or does the `./` make PHP interpret it differently? – jameshfisher Apr 03 '14 at 14:02
  • include paths, probably one of the least understood features of PHP – Mark Baker Apr 03 '14 at 14:11
  • Yes, no, this also does not work. My bad. The `__DIR__` solution is fine. Rather than including files manually you might want to use the autoloading functionality by the way. – Ulrich Thomas Gabor Apr 03 '14 at 14:11

1 Answers1

3

Use __DIR__.

For example:

require __DIR__ .'/file_in_same_directory.php';

http://www.php.net/manual/en/language.constants.predefined.php

halfer
  • 19,824
  • 17
  • 99
  • 186
edmondscommerce
  • 2,001
  • 12
  • 21
  • Ah, okay. Yes, [I can see that that would work](http://www.php.net/manual/en/language.constants.predefined.php). Is there a standard function/statement that abstracts over that, e.g. `require_relative`? – jameshfisher Apr 03 '14 at 14:00
  • what would you want it to do?, eg do you need to `require(__DIR__ .'/../../something_two_dirs_up.php'); sorry markdown is breaking this, you get the idea – edmondscommerce Apr 03 '14 at 14:01
  • I'd expect some PHP statement that basically does: `function require_once_relative($path) { require_once(__DIR__ . $path); }` – jameshfisher Apr 03 '14 at 14:45
  • you can always make it if you think its required. I personally don't like the idea, I would rather just see the path. Also PHPStorm works nicely with autocompleting paths when using `__DIR__` – edmondscommerce Apr 03 '14 at 15:03