php - Meaning of question mark colon operator [dup

2019-06-15 01:36发布

This question already has an answer here:

What does ?: in this line mean?

$_COOKIE['user'] ?: getusername($_COOKIE['user']);

Thank you.

4条回答
时光不老,我们不散
2楼-- · 2019-06-15 02:00

It is short hand php, for example:

(true == true ? echo "this is true" : "this is false")

Written out this means:

if (true == true) {
    echo "This is true";
}
else {
    echo "This is false";
}

In your example, there is only an else statement.

查看更多
The star\"
3楼-- · 2019-06-15 02:04

It's known as the ternary operator, similar to what's commonly called an inline if. For instance, the following two examples:

a) $genderString = $genderAbbreviation == "M" ? "Male" : "Female";

b)

if ($genderAbbreviation == "M")
{
    $genderString = "Male";
}
else
{
    $genderString = "Female";
}

Both of these will have the same effect. The statement before the question mark is evaluated to be either true or false, and then if true the statement before the colon is executed, and if false the statement after the colon is executed.

For more information you can check the section titled "Ternary Operator" on the following page of the PHP documentation:

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

查看更多
手持菜刀,她持情操
4楼-- · 2019-06-15 02:09

if $_COOKIE['user'] value is exist then NULL else getusername($_COOKIE['user'] will work

it's a ternary operator in php

查看更多
地球回转人心会变
5楼-- · 2019-06-15 02:20

It is a shorthand for an if statement.

$username = $_COOKIE['user'] ?: getusername($_COOKIE['user']);

Is the same as

if( $_COOKIE['user'] ) 
{
    $username = $_COOKIE['user'];
} 
else
{
    $username = getusername($_COOKIE['user']); 
}

see test suite here: https://3v4l.org/6XMc4

But in this example, the function 'getusername' probably doesn't work correct, because it hits the else only when $_COOKIE['user'] is empty. So, the parameter inside getusername() is also kind of empty.

查看更多
登录 后发表回答