【问题标题】:PHP exit only current included script file from inside a functionPHP仅从函数内部退出当前包含的脚本文件
【发布时间】:2020-10-19 12:46:59
【问题描述】:

我知道我可以使用return 退出当前脚本文件,但是如果我们想从函数内部退出当前脚本怎么办?

例如,我们定义了一个 exitScript() 函数,它打印关闭的 html 标记并退出当前脚本文件,但如果我们使用 return 它只退出当前函数。 exit() 不仅会终止当前文件,还会终止整个脚本。

【问题讨论】:

  • 您应该只使用return 从函数返回。退出脚本的机制并不重要。
  • 我认为您正在寻找 exit(); 功能。
  • @RiggsFolly 有一种方法可以从函数内退出整个脚本,因此从逻辑上讲,它可以/应该是一种从函数内仅退出当前脚本文件的方法。
  • @Vidal exit() 不仅终止当前文件,还终止整个脚本
  • @Vidal 我知道,这就是我想说的 :)

标签: php function return include exit


【解决方案1】:

您可以将return 从包含的文件转移到“主文件”,跳过return 之后剩余部分的执行。

所以这将输出:ABXend,跳过C

a.php

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

b.php

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

   echo 'C';

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

【讨论】:

  • 这需要手动检查所有x()函数调用,并在它们后面加上return。此外,我们需要在调用他们调用x() 的函数之后放置return,因为我们也不能在这些函数中使用return:)
【解决方案2】:

你可以使用 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.";
    }
}

【讨论】:

  • OP 正在谈论尝试仅退出已包含或要求的文件
  • 感谢这是一个很好的解决方案。此外,如果我们将最后一个代码放在 finally 块中,它甚至会发生致命错误,这超出了我的预期。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 2017-08-27
  • 2022-12-03
相关资源
最近更新 更多