jameshfisher
jameshfisher

Reputation: 36599

How can I make PHP include/require compositional?

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?

Upvotes: 0

Views: 52

Answers (1)

edmondscommerce
edmondscommerce

Reputation: 2011

Use __DIR__.

For example:

require __DIR__ .'/file_in_same_directory.php';

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

Upvotes: 3

Related Questions