Home  >  Article  >  php教程  >  null coalescing operator in PHP

null coalescing operator in PHP

WBOY
WBOYOriginal
2016-07-06 13:31:04889browse

PRoject: blogtarget: null-coalesce-Operator-in-php.mddate: 2015-12-30status: publishtags: - Null Coalesce - PHPcategories: - PHP The null coalesce operator is a good thing, with it we can It is convenient to get a parameter and provide a default value if it is empty. For example, in js

<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 obtain 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 || 'some-default-value';
    // ...
}
</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参数的值(如果为空,则用'nobody')
$username = $_GET['user'] ?? 'nobody';
// 等价于:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
</code>

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

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

The expression (expr1) ? (expr2) : (expr3) has the value expr2 when expr1 evaluates to TRUE and expr3 when expr1 evaluates to FALSE.
As of PHP 5.3, the middle part of the ternary operator can be omitted. The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE and expr3 otherwise.
-- http://php.net/manual/zh/language.operators.comparison.php

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.


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
Previous article:Another week-AJAX (3)Next article:Another week-AJAX (3)