What does ?:
in this line mean?
$_COOKIE['user'] ?: getusername($_COOKIE['user']);
Thank you.
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.
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With