【问题标题】:What is the 'Null coalesce' (??) operator used for? [closed]'Null coalesce' (??) 运算符用于什么? [关闭]
【发布时间】:2015-11-12 07:28:17
【问题描述】:

随着新 PHP 版本 PHP 7 的发布,引入了新功能。在这些新功能中,有一个我不熟悉的运算符。 Null coalesce operator

这个运算符是什么,有哪些好的用例?

【问题讨论】:

  • 来自manual:“已添加空合并运算符 (??) 作为语法糖,用于需要与 isset() 结合使用三元的常见情况。它如果存在且不为 NULL,则返回其第一个操作数;否则返回其第二个操作数。"

标签: php coding-style operators php-7


【解决方案1】:

你可以用它来初始化一个可能为空的变量

??运算符称为空合并运算符。它返回 如果操作数不为空,则为左操作数;否则返回 右手操作数。

来源:https://msdn.microsoft.com/nl-nl/library/ms173224.aspx

(不依赖于语言)

用例

你可以写

$rabbits;

$rabbits = count($somearray);

if ($rabbits == null) {
    $rabbits = 0;
}

你可以使用更短的符号

$rabbits = $rabbits ?? 0;

【讨论】:

    【解决方案2】:

    根据 PHP 手册:

    已添加空合并运算符 (??) 作为语法糖,用于需要将三元组与 isset() 结合使用的常见情况。如果存在且不为 NULL,则返回其第一个操作数;否则返回第二个操作数。

    // Fetches the value of $_GET['user'] and returns 'nobody'
    // if it does not exist.
    $username = $_GET['user'] ?? 'nobody';
    // This is equivalent to:
    $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
    
    // Coalesces can be chained: this will return the first
    // defined value out of $_GET['user'], $_POST['user'], and
    // 'nobody'.
    $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
    

    【讨论】:

      【解决方案3】:
      $username = $_GET['user'] ?? 'nobody'; 
      

      相同

      $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

      ??是三元速记

      【讨论】:

        猜你喜欢
        • 2017-07-13
        • 2014-01-14
        • 2011-02-04
        • 1970-01-01
        • 2012-09-30
        • 2018-02-22
        • 1970-01-01
        • 2012-05-22
        • 2016-09-30
        相关资源
        最近更新 更多