根据php手册:
Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.
我不明白为什么你应该指定目录?
例如我看到了这段代码
<?php
defined("DS") || define("DS", DIRECTORY_SEPERATOR);
defined("ROOT_DIR") || define("ROOT_DIR", realpath(dirname(__FILE__).DS."..".DS));
defined("CLASSES_DIR") || define("CLASSES_DIR", "classes");
set_include_path(implode(PATH_SEPERATOR, array(
realpath(ROOT_DIR.DS.CLASSES_DIR.DS),
get_real_path()
)));
?>
为什么将 CLASSES_DIR 添加到包含路径?你不能已经做类似 require("classes/example.php") 的事情了吗?
最佳答案
通过设置包含路径,您不再需要显式指定文件的完整路径,因为 php 有一些选项来照顾您的“example.php”。假设您的“DOCUMENT_ROOT/classes”目录中有一个名为“exampleClass.php”的 php 文件,并且直接在 DOCUMENT_ROOT 下有一个 index.php:
<?php
set_include_path(DOCUMENT_ROOT . DIRECTORY_SEPARATOR . 'classes');
// Note that exampleClass.php is not located in the same directory as this index.php
require('exampleClass.php');
?>
但我想补充一点,在所描述的示例中,可能有更好的选择来组织和构建项目以避免“require(/hope/this/path/is/the/right/one.php)”语句。例如。通过使用 namespaces与 autoloading 结合
关于php - set_include_path() 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129117/