如何从PHP中的特定功能退出?

时间:2018-10-29 15:04:45

标签: php

我在PHP类中有多个嵌套方法。我想做的是,在某些情况下,我想从NOT JUST退出当前方法,但要退出上面的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.";
        }
    }
}

就像代码注释中提到的那样,我想破坏脚本-如果随机数小于50,然后返回fn1(),但继续在其中执行echo函数。

这有可能吗?请让我知道是否需要更多信息,我会提供。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

使用flag进行常规函数调用怎么样?

class Sites
{
    protected $flag  = false; 
    public function __construct()
    {
        $this->fn1();
    }


    public function fn1()
    {

        if ($this->flag) {
            $this->flag = true;

        } else {
            echo 'I want this to be displayed no matter what!';
            $fn2 = $this->fn2();
        }

    }

    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();
        $this->flag = true;
        $this->fn1();
        exit();

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

$sites = new Sites;

我希望这会有所帮助!