Question

I'm trying to find the ideal way to integrate files into others throughout a directory hierarchy in my project.

I've noticed that the following works in Eclipse PDT:

  1. require_once '/../../services/impl/UserService.php';
  2. require_once ('ui/controller/AbstractController.php');
  3. require_once $_SERVER['DOCUMENT_ROOT'] . '/myproject/daos/impl/UserDAO.php';
  4. require_once dirname(__FILE__) . '/../AsbtractDAO.php';

All of these resolve yet the way they're formulated is completely different. Any ideas why ?

In particular the path in brackets (2) resolves but doesn't when the same path is between single quotes.

Also, what are the pros/cons of each ? What standard could I adopt that's the most robust ?

Was it helpful?

Solution

For the first two, I'm guessing you're asking about whether or not to use parenthesis. For that, take a look at this answer: When should I use parenthesis in require/include statements? Essentially you can use either, but for readability it's best to be consistent, whichever you choose. The first style seems to be more common.

Using absolute paths can speed up performance, since using a relative path will instruct PHP to look through everything in the include_path. Require can accept either a relative or absolute, much like any other language's include calls.

The third will pass an absolute path to the require. However, there are potential issues with $SERVER['DOCUMENT_ROOT'] (e.g. it doesn't work on some IIS servers).

In the fourth you're using the file's absolute path from dirname(__FILE__) -- also __DIR__ in PHP >= 5.3. You can also do this by defining a constant with the path. If you're going for code golf, this would be the most keystrokes, but it may improve performance, depending on how many files would need to be scanned in your include_path when importing a relative location.

Summary:

  1. Pros: easiest to read. Cons: may be slower due to use of relative paths
  2. Same as 1 - stylistic difference only.
  3. Pros: may be faster due to use of absolute paths. Cons - won't work on some web servers
  4. Pros: may be faster due to use of absolute paths. Cons - more long-winded
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top