Reputation: 1437
I have the following directories and files:
└── project
├── index.php
└── lib
├── file1.php
└── file2.php
<?php
//index.php
include 'lib/file1.php';
<?php
//file1.php
include 'lib/file2.php';
<?php
//file2.php
echo 'this is from an echo statement in file2.php';
This does work when I try it in the browser as I expected. In particular I think the include statement in file1.php makes sense because it uses a path to file2.php relative to the location of index.php which includes file1.php and so is the location that file1.php's code will be executed.
However, I was surprised that if I change the include statement in file1.php to:
include 'file2.php';
it still works.
I would like to understand why both include statements work and get an idea of which of the two is the more correct.
Upvotes: 3
Views: 65
Reputation: 224
According to the include documentation
Files are included based on the file path given or, if none is given, the include_path specified
The PHP parser would also look at file1's directory for file2 even if it was included from index's directory.
In file1.php the correct way to include it would be
include 'file2.php';
Because it would allow you to include file1.php from anywhere, not just 'project' directory:
include 'lib/file2.php';
Would not work if you decided to create another directory and include file1.php there (../file1.php)
Upvotes: 1
Reputation: 33573
From the documentation (emphasis mine):
If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.
file1.php
's own directory is lib
, and it can find file2.php
there.
Upvotes: 4