标签:include_once

共 1 篇相关文章

IT 累计浏览 6,768

再一次, 不要使用(include/require)_once

关于 apc.include_once_override 的去留讨论,引出了一个关于 include 与 include_once 选择的老话题。一般认为尽量用 include 而非 include_once,理由是 include_once 需要查询已加载文件列表,但更有说服力的原因在于其实现机制:PHP 判断文件是否已加载需要得到 opened_path,因此在 include_once 时会先尝试 open 这个文件(比如通过 include_path 定位到 /tmp2/2.php),拿到 opened_path 后再去 EG(included_files) 查找,未包含才进入 compile_file。大多数情况这不是问题,但使用 APC 时 APC 劫持了 compile_file 以直接从缓存取编译结果、避免 open 的系统调用,而 include_once 在进入被劫持的 compile_file 之前已经 open 过文件,就产生了一次额外的 open。为此 APC 才引入 include_once_override,通过劫持 ZEND_INCLUDE_OR_EVAL opcode handler、用 stat 确定绝对路径并把 opcode 改写为 include,算是 tricky 方案。

抛开技术因素,作者认为我们完全能自己规划让一个文件只被加载一次,也可借助自动加载;使用 include_once 只能证明你对自己的代码没信心。建议不要再使用 include_once。