如何退出 PHP 中的特定函数?

Rad*_*ity 1 php

我在 PHP 类中有多个嵌套方法。我想要做的是,基于某些情况,我想退出不仅仅是当前方法,而是退出它上面的 2,然后剩余的代码应该继续运行。现在 die()、exit() 的问题是它们结束了完整的脚本,而我不想要那样。我只是想使用一些方法并继续编写脚本。

当然,在每个方法中都有返回一个值并检查它是否为假的老派方法。但是那样的话,如果我有 50 个嵌套方法,我将不得不编写大量的附加代码。这是我现在所拥有的 - 这是一个非常基本的用法,我在更复杂的场景中使用它(使用 PHP 7.2.4):

class Sites
{
    public function __construct()
    {
        $this->fn1();
    }

    public function fn1()
    {   
        $fn2 = $this->fn2();

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

    public function fn2()
    {       
        $fn3 = $this->fn3();

        if ($fn3)
        {
            return true;
        }
    }

    public function fn3()
    {       
        $fn4 = $this->fn4();

        if ($fn4)
        {
            return true;
        }
    }

    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();

            echo "This shouldn't be displayed.";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如代码注释中提到的,我想破坏脚本 - 如果随机数低于 50 并返回fn1()但继续在echo那里执行函数。

这有可能吗?如果您需要更多信息,请告诉我,我会提供。

Nig*_*Ren 5

您可以使用 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.";
    }
}
Run Code Online (Sandbox Code Playgroud)