Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - Meaning of question mark colon operator [duplicate]

Tags:

What does ?: in this line mean?

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

Thank you.

like image 245
Lewis Avatar asked May 20 '14 07:05

Lewis


People also ask

What does double question mark operator mean in PHP?

operator. In PHP 7, the double question mark(??) operator known as Null Coalescing Operator. It returns its first operand if it exists and is not NULL; otherwise, it returns its second operand. It evaluates from left to right.

What does the question mark mean in PHP?

Nullable types ¶ Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, null can be passed as an argument, or returned as a value, respectively.

What does question mark colon mean?

Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

What is the colon operator in PHP?

In PHP, the double colon :: is defined as Scope Resolution Operator. It used when when we want to access constants, properties and methods defined at class level. When referring to these items outside class definition, name of class is used along with scope resolution operator.


2 Answers

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.

like image 191
trizz Avatar answered Oct 17 '22 08:10

trizz


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.

like image 20
Arko Elsenaar Avatar answered Oct 17 '22 09:10

Arko Elsenaar