在 php 中如何处理 include_once 循环?

How are include_once loops handled in php?

我有 3 个不同的文件-

  1. fileMainIncludeEverywhere.php

    ...
    include_once('fileMinorInclude.php');
    ?>
    
  2. fileMinorInclude.php

    ...
    include_once('fileMainIncludeEverywhere.php');
    ...
    
  3. fileToRun.php

    ...
    include_once('fileMainIncludeEverywhere.php');
    ...
    

我有很多像 fileToRun.php.

这样的文件

目前我的代码中没有遇到任何错误,但我想知道这是否会失败?

我认为在这种情况下没有错误。因为 include_once 只会在第一次加载该文件,所以即将到来的同一文件的加载请求将被拒绝。

所以从你的例子来看:

  1. fileToRun.php 将加载 fileMainIncludeEverywhere.php(第一次调用)
  2. fileMainIncludeEverywhere.php 将加载 fileMinorInclude.php(第一次调用)
  3. fileMinorInclude.php 将调用加载 fileMainIncludeEverywhere.php 但它将被拒绝,因为它已在第一步中加载。

希望对您有所帮助。

include_once:

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once.

这里"code from a file"也包含执行的PHP文件。

请注意,通常最佳做法是使用 require_once() 而不是 include_once(),除非您有使用 include_once() 的特定原因(比如包括可选模板组件)。这是因为如果找不到所需的资源,require_once() 将终止 (fail fast),正常情况下找不到它应该是终端故障。