【问题标题】:what does set_include_path() do?set_include_path() 是做什么的?
【发布时间】:2015-07-19 16:21:45
【问题描述】:

根据php手册:

指定 require、include、fopen()、file()、readfile() 和 file_get_contents() 函数查找文件的目录列表。格式类似于系统的 PATH 环境变量:在 Unix 中用冒号分隔的目录列表,在 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") 的事情吗?

【问题讨论】:

  • 在执行require("classes/example.php") 时,您正在尝试获取与current working dir 相关的文件,该文件可以更改。

标签: php


【解决方案1】:

通过设置包含路径,您不再需要明确指定文件的完整路径,因为 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 结合使用

【讨论】:

  • 加一个用于自动加载。 PSR-4 和 Composer 简直是那么好
  • 我绝对同意它是无价的
  • 回答我完全理解 set_include_path() 背后的逻辑
  • 这段代码实际上来自我正在关注的一个php教程,作者同时使用了set_include_path和autoload,那是什么意思?
  • 能否请您发布该教程的链接?
猜你喜欢
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 2011-11-07
  • 2011-11-01
  • 2010-11-24
  • 2015-04-27
相关资源
最近更新 更多