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?

4
  • 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. Commented Apr 3, 2014 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? Commented Apr 3, 2014 at 14:02
  • include paths, probably one of the least understood features of PHP Commented Apr 3, 2014 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. Commented Apr 3, 2014 at 14:11

1 Answer 1

3

Use __DIR__.

For example:

require __DIR__ .'/file_in_same_directory.php';

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ah, okay. Yes, I can see that that would work. Is there a standard function/statement that abstracts over that, e.g. require_relative?
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
I'd expect some PHP statement that basically does: function require_once_relative($path) { require_once(__DIR__ . $path); }
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__

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.