Is there a short-circuit OR in PHP that returns the left-most value?

前端 未结 6 2044
南笙
南笙 2020-12-09 16:57

In some languages, you can do

$a = $b OR $c OR die(\"no value\");

That is, the OR will short-circuit, only evaluating values from left to right

相关标签:
6条回答
  • 2020-12-09 17:02

    No, there isn't, and this is, in my opinion, one of the bad decisions that Rasmus Lerdorf made in designing PHP that most hobbles competent developers for the sake of coddling incompetent ones.

    Edit: In PHP 5.3 and up, you can write $a = $b ?: $c, and even $a = $b ?: $c ?: $d. Still not as good as non-brain-damaged logical operators, but it's something.

    0 讨论(0)
  • 2020-12-09 17:12

    You could use some kind of coalesce function:

    function coalesce() {
        foreach (func_get_args() as $arg) {
            if ($arg) {
                return $arg;
            }
        }
        return null;
    }
    
    $a = coalesce($a, $b) or die("no value");
    
    0 讨论(0)
  • 2020-12-09 17:15

    This should work:

    $a = (($f1=func1()) ? $f1 : ($f2=func2()) ?  $f2 : func3()) );
    
    0 讨论(0)
  • 2020-12-09 17:19

    What about variable functions?

    function coalesce($funcs)
    {
        foreach ($funcs as $func)
        {
            //Catch language constructs
            switch($func)
            {
                case 'die':
                    die();
            }
            $result = $func();
            if ($result)
            {
                return $result;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-09 17:19

    I'm sorry, but most of these answer are just off.

    $a = $b OR $c OR die("no value");

    becomes

    $a = $b ?: $c ?: die("no value");
    

    The reason OR doesn't work is that instead instead of returning the former or latter value it returns true or false.

    0 讨论(0)
  • 2020-12-09 17:24

    You can use just:

    $a = func1() or $a = func2() or $a = func3();
    

    or am I missing something?

    0 讨论(0)
提交回复
热议问题