基于PHP的文档,我希望以下文件层次结构
.
├── autoload.php
└── etc
└── php-lib
├── autoload.php
└── common.php
2 directories, 3 files
以及以下内容:
cat autoload.php
<?php
echo "I am the wrong autoloader";
cat etc/php-lib/autoload.php
<?php
echo "This is the right one!";
cat etc/php-lib/common.php
<?php
include_once('autoload.php');
我跑步时
$ php etc/php-lib/common.php
我将得到以下输出:
This is the right one!
我希望这是因为手册指出:
Files are included based on the file path given or, if none is given, the
include_path specified. 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. The include construct will emit
a warning if it cannot find a file; this is different behavior from
require, which will emit a fatal error.
但是,我得到了:
I am the wrong autoloader
那么为什么要加载autoload.php
而不是etc/php-lib/autoload.php
?
实际上,当我跟踪此内容时,包含顺序似乎比根据手册的预期还要奇怪:
第一种情况,上述所有文件都存在
getcwd("/home/hvdb/temp2", 4096) = 17
lstat("/home/hvdb/temp2/./autoload.php", {st_mode=S_IFREG|0644, st_size=40, ...}) = 0
lstat("/home/hvdb/temp2/autoload.php", {st_mode=S_IFREG|0644, st_size=40, ...}) = 0
openat(AT_FDCWD, "/home/hvdb/temp2/autoload.php", O_RDONLY) = 3
我们看到PHP首先在cwd中寻找autoload.php
。
如果删除该文件,即./autoload.php
,则会得到以下信息:
getcwd("/home/hvdb/temp2", 4096) = 17
lstat("/home/hvdb/temp2/./autoload.php", 0x7fff7f04e880) = -1 ENOENT (No such file or directory)
lstat("/usr/share/php/autoload.php", 0x7fff7f04e880) = -1 ENOENT (No such file or directory)
lstat("/home/hvdb/temp2/etc/php-lib/autoload.php", {st_mode=S_IFREG|0644, st_size=38, ...}) = 0
然后我才看到PHP(仍然首先检查cwd中的autoload.php
)在include_directories中设置的目录,然后在调用脚本目录中查看autoloader.php
。
那么,说明文件是否错误,或者我误解了手册?
答案 0 :(得分:1)
从评论来看,问题在于您已将php.ini文件中的include_path
设置为默认设置。就您而言,.
这就是为什么最好在脚本中有一个配置文件,以便您在其中创建如下常量:
PHP> = 5.3.0
define("PATH", __DIR__);
PHP <5.3.0
define("PATH", dirname(__FILE__));
这将使您可以控制要从当前工作目录中包含的文件,并确保脚本仍可以在其他环境中工作,而您可能无法控制PHP的配置。