PHP's null merge operator project: blogtarget: null-coalesce-operator-in-php.mddate: 2015-12-30status: publishtags:-NullCoalesce-PHPcategories:-PHPnull merge operator is a good thing, with this, we can easily use the null merge operator in PHP.
project: blogtarget: null-coalesce-operator-in-php.mddate: 2015-12-30status: publishtags: - Null Coalesce - PHPcategories: - PHP
The null merge operator is a good thing. with it, we can easily obtain a parameter and provide a default value when it is null. For example, you can use||
Here:
function setSomething(a){ a = a || 'some-default-value'; // ...}
In PHP, it's a pity that||
Always returntrue
Orfalse
.
PHP7 was officially added.??
This operator:
// Obtain the value of the user parameter (if it is null, use 'nobody') $ username = $ _ GET ['user']? 'Nobody'; // equivalent to: $ username = isset ($ _ GET ['user'])? $ _ GET ['user']: 'Nobody ';
PHP7 is estimated to be used in the production environment for a long time. Is there any alternative solution in the current PHP5?
According to research, there is a very convenient alternative:
// Obtain the value of the user parameter (if it is null, use 'nobody') $ username = @ $ _ GET ['user']? : 'Nobody'; // equivalent to: $ username = isset ($ _ GET ['user'])? $ _ GET ['user']: 'Nobody ';
-- Run this code: https://3v4l.org/aDUW8
With a Wide Eye, the above PHP7 example is similar, mainly??
To?:
. What is this? In fact, this is(expr1) ? (expr2) : (expr3)
Expression omitting mode:
Expression (expr1 )? (Expr2): (expr3) when the value of expr1 is TRUE, the value is expr2, and when the value of expr1 is FALSE, the value is expr3.
From PHP 5.3, the portion in the middle of the ternary operator can be omitted. Expression expr1? : Expr3 returns expr1 when the value of expr1 is TRUE; otherwise, expr3 is returned.
Http://php.net/manual/zh/language.operators.comparison.php
Of course, this alternative is not perfect-if$_GET
Not in'user'
, There will be oneNotice: Undefined index: user
So you need to use@
To suppress or disable this error.E_NOTICE
.