简体   繁体   English

PHP 仅从 function 中退出当前包含的脚本文件

[英]PHP exit only current included script file from inside a function

I know I can use return to exit current script file, but what if we want to exit current script from inside a function?我知道我可以使用return退出当前脚本文件,但是如果我们想从 function 中退出当前脚本怎么办?

For example, we define a exitScript() function that prints closing html tags and exits current script file, but if we use return it only exits from current function.例如,我们定义了一个exitScript() function 打印关闭 html 标记并退出当前脚本文件,但如果我们使用return它只会从当前 ZC1C425268E68385D1AB5074C17A94 退出。

You can use Exceptions to do this, not particularly elegant, but this should do what your after, replace these methods.您可以使用 Exceptions 来做到这一点,不是特别优雅,但这应该做您之后的事情,替换这些方法。

public function fn1()
{
    try {
        $fn2 = $this->fn2();
    }
    catch ( Exception $e )  {
    }

    echo 'I want this to be displayed no matter what!';
}


public function fn4()
{
    $random = rand(1, 100);

    if ($random > 50)
    {
        return true;
    }
    else
    {
        // I want to exit/break the scirpt to continue running after
        // the $fn2 = $this->fn2() call in the $this->fn1() function.
        //exit();
        throw new Exception();

        echo "This shouldn't be displayed.";
    }
}

You can return from an included file to the 'main file', skipping execution of the remaing part after the return .您可以从包含的文件return到“主文件”,在return之后跳过剩余部分的执行。

So this will output: ABXend , skipping C所以这将 output: ABXend ,跳过C

a.php a.php

<?php 
  echo 'A';
  include('b.php');
  echo 'end';
?>

and b.phpb.php

<?php 
   echo 'B';
   if(!x(6))return; //return here

   echo 'C';

   function x($num){
     echo 'X';
     if($num!==1)return false;
     }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM