Assigning variables by reference and ternary operator?

前端 未结 1 1440
闹比i
闹比i 2021-01-12 20:12

Why ternary operator doesn\'t work with assignment by reference?

$obj     = new stdClass(); // Object to add
$result  = true; // Op result
$success = array()         


        
相关标签:
1条回答
  • 2021-01-12 21:06

    Here you go

    $target = ($result ? &$success : &$errors);
    

    Also your example has two typos


    edit

    http://php.net/manual/en/language.operators.comparison.php

    Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

    idk if this worked before, but it doesn't anymore. if you don't wanna use an if statement, then try this:

    $result ? $target = &$success : $target = &$errors;
    

    or on separated lines ...

    $result 
      ? $target = &$success 
      : $target = &$errors;
    
    0 讨论(0)
提交回复
热议问题