我知道如何将文件夹中的文件包含在内,但我很难找到备份的方式。我决定将 set_include_path 设置为默认值,所有进一步包括相对于路径 2 级以上的路径,但丝毫不知道如何将其写出来。
是否有详细说明 PHP 路径引用的指南?
我知道如何将文件夹中的文件包含在内,但我很难找到备份的方式。我决定将 set_include_path 设置为默认值,所有进一步包括相对于路径 2 级以上的路径,但丝毫不知道如何将其写出来。
是否有详细说明 PHP 路径引用的指南?
我倾向于使用dirname来获取当前路径,然后以此为基础来计算所有未来的路径名。
例如,
$base = dirname( __FILE__ ); # Path to directory containing this file
include( "{$base}/includes/Common.php" ); # Kick off some magic
使用绝对路径来引用可能更容易:
set_include_path('/path/to/files');
这样,您就有了所有未来的参考点。包含相对于它们被调用的点进行处理,这在某些情况下可能会引起一些混乱。
例如,给定一个示例文件夹结构 ( /home/files
):
index.php
test/
test.php
test2/
test2.php
// /home/files/index.php
include('test/test.php');
// /home/files/test/test.php
include('../test2/test2.php');
如果您调用 index.php,它将尝试包含以下文件:
/home/files/test/test.php // expected
/home/test2/test2.php // maybe not expected
这可能不是您所期望的。调用 test.php 将按/home/files/test2/test.php
预期调用。
结论是,包含将相对于原始调用点。澄清一下,这也会影响set_include_path()
它是否是相对的。考虑以下(使用相同的目录结构):
<?php
// location: /home/files/index.php
set_include_path('../'); // our include path is now /home/
include('files/test/test.php'); // try to include /home/files/test/test.php
include('test2/test2.php'); // try to include /home/test2/test2.php
include('../test3.php'); // try to include /test3.php
?>