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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-10-11 14:23:37
Original
1161 people have browsed it

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?

function test($var){
  return $var == 42 ? 1 : 2;
}

echo test(40);    //2
Copy after login
Copy after login

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?

function test($var){
  return $var == 42 ? 1 : 2;
}

echo test(40);    //2
Copy after login
Copy after login

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

<?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;
}
Copy after login
Related labels:
php
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template