【问题标题】:How to include files with die(); function?如何使用 die() 包含文件;功能?
【发布时间】:2010-12-19 23:18:57
【问题描述】:

file1.php 和 file2.php 与 die();功能。

include.php:

<? include 'file1.php';
include 'file2.php' ?>

file1.php

<? echo 'included'; die(); ?>

file2.php

<? echo 'not included'; die(); ?>

如何将两个文件都包含在 die();功能?

【问题讨论】:

  • file1.php和file2.php末尾的die()的作用是什么?如果您想停止执行包含的文件,您可以改用return

标签: php file function include die


【解决方案1】:

非英语使用者:

您也可以用您的母语提供您的问题,这里可能会有人为您翻译。请尽量用英语提问,并在下方添加您的母语。


如果你想测试include是否成功,可以测试include函数本身的返回值:

// http://us3.php.net/manual/en/function.include.php Example #4
if ((include 'file1.php') != 'OK') {
    die();
}

您也可以根据需要考虑require() 而不是 include():

require() 与 include() 相同,但失败时也会产生致命的 E_ERROR 级错误。换句话说,它将停止脚本,而 include() 只发出一个警告 (E_WARNING) 允许脚本继续。

【讨论】:

    【解决方案2】:

    如果我正确理解您要做什么,那么很遗憾,这是不可能的。

    die(); 将停止脚本在调用它的位置执行。

    【讨论】:

      【解决方案3】:

      这里是如何包含一个文件,或者如果包含失败代码示例,则会显示一条消息。

      (include('file.php')) || die('Failed to include file!');
      

      【讨论】:

        【解决方案4】:
        if (!condition){
           include_once('./inc/header.inc.php');
           echo "Errormessage";
           include_once('./inc/footer.inc.php');
           die();
        }
        

        我希望这是你想要的。

        【讨论】:

          【解决方案5】:

          如果你的包含文件的执行不依赖于当前文件(没有共享变量、函数等),那么使用

          file_get_contents('link_to_file.php');
          

          而不是包含方法。当您强制文件独立执行时,它不会影响脚本执行。

          【讨论】:

            【解决方案6】:

            只是对LorenzoP的方法的一个小改进:

            
            (@include("file.php")) or die("Failed to include!");
            // notice the @ sign!
            
            

            这样,当包含失败时,您可以节省 2 行难看的 php 警告。否则,我认为这确实是处理失败包含的最佳方法。 (另外,他的答案应该是被接受的。)

            【讨论】:

              【解决方案7】:

              die() 只是一个有错误的退出,你不能在其中包含文件,我真的不明白你为什么要这样做。您能否提供更多关于您要完成的工作的详细信息?

              【讨论】:

                猜你喜欢
                • 2013-03-23
                • 1970-01-01
                • 1970-01-01
                • 2021-12-28
                • 1970-01-01
                • 2022-07-06
                • 1970-01-01
                • 1970-01-01
                • 2018-06-02
                相关资源
                最近更新 更多