Home >Backend Development >PHP Tutorial >I don't understand the precautions for the ternary operator in the PHP documentation

I don't understand the precautions for the ternary operator in the PHP documentation

WBOY
WBOYOriginal
2016-10-11 14:23:371134browse

Note: Note that the ternary operator is a statement, so its evaluation is not a variable, but the result of the statement. This is important if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a function that returns by reference will not work, and a future version of PHP will issue a warning about this.

return $var == 42 ? $a : $b; What does it mean if it doesn’t work? Is it impossible to return a value or something?

<code class="php">function test($var){
  return $var == 42 ? 1 : 2;
}

echo test(40);    //2</code>

This way you can return it during testing...

Reply content:

Note: Note that the ternary operator is a statement, so its evaluation is not a variable, but the result of the statement. This is important if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a function that returns by reference will not work, and a future version of PHP will issue a warning about this.

return $var == 42 ? $a : $b; What does it mean if it doesn’t work? Is it unable to return a value or something?

<code class="php">function test($var){
  return $var == 42 ? 1 : 2;
}

echo test(40);    //2</code>

This way you can return it during testing...

Affects the scenario of "returning a variable by reference"

See the example, get2 cannot achieve the expected results

https://3v4l.org/2Q9ai

<code class="php"><?php

$data = new stdClass;
$data->a = 13;
$data->b = 42;

$var = &get1($data, true);
$var = 14;
var_dump($data);

$var2 = &get2($data, false);
$var2 = 43;
var_dump($data);

function &get1($data, $isA) {
    if($isA) {
        return $data->a;
    } else {
        return $data->b;
    }
}

function &get2($data, $isA) {
    return $isA ? $data->a : $data->b;
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn