IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

include(“./file.php”)和include(“file.php”)区别

将之典藏 2011-09-19 23:24:32 累计浏览 12,721 次
本机暂存

    多数情况下,两种方式的区别可能在性能上有细微的区别(via)。 但是,在多重包含的情况下表现未必一样:

|-- index.php
`-- lib
    |-- a.php
    `-- b.php

    假定有三个文件,入口文件index.php,包含lib/a.php。a.php又需要包含它同目录下的b.php:

  • 方式1:include(“./b.php”) - 不工作
  • 方式2:include(“b.php”) - 正常
  •     我们通过strace来跟踪一下方式2的系统调用(我的环境下include_path=.:/tmp):

    open("/home/robin/devel/lib/a.php", O_RDONLY) = 3
    open("/home/robin/devel/b.php", O_RDONLY) = -1 ENOENT (No such file or directory)
    open("/tmp/b.php", O_RDONLY)            = -1 ENOENT (No such file or directory)
    open("/home/robin/devel/lib/b.php", O_RDONLY) = 3

        官方文档的阐述是这样的:

        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.

        所以优先级应该是这样:

  • 有指定路径的话(如:”./”或者是”../”或”/home/…”),将直接根据路径来查找文件;
  • 没有指定路径的情况
  • 遍历include_path查找,include_path中有“.”开头的话,则指的是CWD(Current working directory,即是例中的index.php所在的目录)
  • 在calling script(也就是例中的a.php)所在的目录查找
  • 在CWD目录查找 - 不过在测试的时候发现似乎没有做到这一样。很容易测试:把include_path设成”/”避免其中有“.”,也就避免根据include_path方式查找到文件,再把b.php移到index.php同一级目录,结果包含不到。
  • 当然,比较推荐结合魔术常量__FILE__来include。

    参考及延伸阅读:

  • What does the dot-slash do to PHP include calls?. StackOverflow
  • PHP官方文档
  • 同分类推荐文章

    1. Vibe新开源项目 - Vaala AI Gateway (2026-05-17 02:10:19)
    2. SmartPerfetto 架构文章 Q&A:8 个深度技术问答 (2026-04-10 11:00:00)
    3. 让 AI 把我的 PHP 博客重写成 Go (2026-03-27 18:33:54)

    查看更多 后端 文章 →

    建议继续学习

    1. 如何成为Python高手 (累计阅读 54,902)
    2. 使用gettext来支持PHP的多语言 (累计阅读 39,187)
    3. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,086)
    4. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,341)
    5. 我的PHP,Python和Ruby之路 (累计阅读 13,066)
    6. Linux 性能监控、测试、优化工具 (累计阅读 12,948)
    7. 15个最好的免费开源电子商务平台 (累计阅读 12,461)
    8. Redis消息队列的若干实现方式 (累计阅读 12,002)
    9. 到底什么是MVC? (累计阅读 11,696)
    10. 整理了一份招PHP高级工程师的面试题 (累计阅读 11,448)