php - set_include_path() 的作用是什么?

标签 php

根据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)”语句。例如。通过使用 namespacesautoloading 结合

关于php - set_include_path() 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129117/

相关文章:

php - 使用 PHP 代码将 mysql 表导出为 CSV

php - 使用 PHP 变量作为 MySQL 中的表名

php - 将 WAMP 与 LDAP 结合使用时出错

php - 在 htaccess 中为用户配置文件创建重写规则

php - 安装 symfony-cmf-standard 时出现 "An error occured when executing the cache:clear --no-warmup"

php - 使用 php curl http post 在 ownCloud 上创建用户

php - 使用 Curl Php SSL 身份验证的 400 错误请求

php - 在 Eloquent 关系中使用 withTrashed

PHP/MySQL : how to display the words before and after the searched item

php - 试图在从 php 脚本发送的短信中获取新行