Home  >  Article  >  Backend Development  >  null coalescing operator in PHP, PHP null coalescing operator_PHP tutorial

null coalescing operator in PHP, PHP null coalescing operator_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 09:02:14738browse

null coalescing operator in PHP, PHP null coalescing operator

<code class="language-meta">project: blog
target: null-coalesce-operator-in-php.md
date: 2015-12-30
status: publish
tags:
    - Null Coalesce
    - PHP
categories:
    - PHP
</code>

The null coalescing operator is a good thing. With it, we can easily get a parameter and provide a default value when it is empty. For example, you can use || in js:

<code class="language-js">function setSomething(a){
    a = a || &#39;some-default-value&#39;;
    // ...
}
</code>

In PHP, unfortunately, PHP's || always returns true or false, so it cannot be done this way.
PHP7 has only officially added the ?? operator:

<code class="language-php">// 获取user参数的值(如果为空,则用&#39;nobody&#39;)
$username = $_GET[&#39;user&#39;] ?? &#39;nobody&#39;;
// 等价于:
$username = isset($_GET[&#39;user&#39;]) ? $_GET[&#39;user&#39;] : &#39;nobody&#39;;
</code>

It is estimated that PHP7 will take a long time to be used in the production environment. So are there any alternatives to the current PHP5?
According to research, there is a very convenient alternative:

<code class="language-php">// 获取user参数的值(如果为空,则用&#39;nobody&#39;)
$username = @$_GET[&#39;user&#39;] ?: &#39;nobody&#39;;
// 等价于:
$username = isset($_GET[&#39;user&#39;]) ? $_GET[&#39;user&#39;] : &#39;nobody&#39;;
</code>

-- Run this code: https://3v4l.org/aDUW8

I looked at it with my eyes wide open. It was similar to the previous PHP7 example, mainly replacing ?? with ?: . What the hell is this? In fact, this is the omission pattern of the (expr1) ? (expr2) : (expr3) expression:

<p>表达式 (expr1) ? (expr2) : (expr3) 在 expr1 求值为 TRUE 时的值为 expr2,在 expr1 求值为 FALSE 时的值为 expr3。<br/>
自 PHP 5.3 起,可以省略三元运算符中间那部分。表达式 expr1 ?: expr3 在 expr1 求值为 TRUE 时返回 expr1,否则返回 expr3。<br/>
-- http://php.net/manual/zh/language.operators.comparison.php</p>

Of course, this alternative is not perfect - if there is no $_GET in 'user', there will be an Notice: Undefined index: user error, so you need to use @ to suppress this error, or turn off E_NOTICE mistake.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1086207.htmlTechArticlenull coalescing operator in PHP, PHPnull coalescing operator project: blogtarget: null-coalesce-operator-in- php.mddate: 2015-12-30status: publishtags: - Null Coalesce - PHPcategories: - P...
Statement:
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