PHP三元运算符和空合并运算符。

时间:2021-08-11 22:29:28

Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

有人能解释一下PHP中三元运算符(?:)和空合并运算符(?)之间的区别吗?

When do they behave differently and when in the same way (if that even happens)?

他们什么时候会有不同的行为,什么时候会以同样的方式(如果这种情况发生的话)?

$a ?: $b

VS.

VS。

$a ?? $b

9 个解决方案

#1


132  

When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say:

当第一个参数为空时,它们基本上是相同的,只是当你有一个未定义的变量时,null合并不会输出一个E_NOTICE。PHP 7.0迁移文档中有如下内容:

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

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

Here's some example code to demonstrate this:

这里有一些示例代码来演示这一点:

<?php

$a = null;

print $a ?? 'b';
print "\n";

print $a ?: 'b';
print "\n";

print $c ?? 'a';
print "\n";

print $c ?: 'a';
print "\n";

$b = array('a' => null);

print $b['a'] ?? 'd';
print "\n";

print $b['a'] ?: 'd';
print "\n";

print $b['c'] ?? 'e';
print "\n";

print $b['c'] ?: 'e';
print "\n";

And it's output:

输出:

b
b
a

Notice: Undefined variable: c in /in/apAIb on line 14
a
d
d
e

Notice: Undefined index: c in /in/apAIb on line 33
e

The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.

有通知的行是我使用速记三元运算符而不是空合并运算符的行。但是,即使有通知,PHP也会返回相同的响应。

Execute the code: https://3v4l.org/McavC

执行代码:https://3v4l.org/McavC

Of course, this is always assuming the first argument is null. Once it's no longer null, then you end up with differences in that the ?? operator would always return the first argument while the ?: shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.

当然,它总是假设第一个参数为null。一旦它不再为空,那么你就会得到不同的值?操作符总是返回第一个参数,而?:速记只有在第一个参数是真实的情况下才会返回,这依赖于PHP如何将数据类型转换为布尔值。

So:

所以:

$a = false ?? 'f';
$b = false ?: 'g';

would then have $a be equal to false and $b equal to 'g'.

然后a = false b = g。

#2


36  

If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:

如果您使用这样的快捷三元运算符,如果$_GET['username']没有设置,将会引起通知:

$val = $_GET['username'] ?: 'default';

So instead you have to do something like this:

所以你必须做这样的事情:

$val = isset($_GET['username']) ? $_GET['username'] : 'default';

The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:

null coalescing运算符等价于上述语句,如果$_GET['username']未设置或为null,则返回'default':

$val = $_GET['username'] ?? 'default';

Note that it does not check truthiness. It checks only if it is set and not null.

注意,它不检查真实性。它只检查它是否被设置为非空。

You can also do this, and the first defined (set and not null) value will be returned:

您也可以这样做,第一个定义的(set和not null)值将返回:

$val = $input1 ?? $input2 ?? $input3 ?? 'default';

Now that is a proper coalescing operator.

这是一个合适的合并运算符。

#3


13  

The major difference is that

主要的区别在于

  1. Ternary Operator expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2) evaluates to expr1 if expr1 is not NULL

    三元运算符表达式expr1 ?: expr3返回expr1,如果expr1计算为TRUE,但另一方面,expr1是否为空?(expr2)如果expr1不是NULL,则计算为expr1

  2. Ternary Operator expr1 ?: expr3 emit a notice if the left-hand side value (expr1) does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2) In particular, does not emit a notice if the left-hand side value (expr1) does not exist, just like isset().

    三元运算符expr1 ?: expr3会发出通知,如果左边的值(expr1)不存在,但另一方面,零合并运算符(expr1) ?(expr2)特别地,如果不存在左侧值(expr1),则不会发出通知,就像isset()一样。

  3. TernaryOperator is left associative

    TernaryOperator剩下的联想

    ((true ? 'true' : false) ? 't' : 'f');
    

    Null Coalescing Operator is right associative

    空联合运算符是正确的联合运算符

    ($a ?? ($b ?? $c));
    

Now lets explain the difference between by example :

现在让我们通过例子来解释两者的区别:

Ternary Operator (?:)

三元操作符(?)

$x='';
$value=($x)?:'default';
var_dump($value);

// The above is identical to this if/else statement
if($x){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Null Coalescing Operator (??)

空合并操作符(? ?)

$value=($x)??'default';
var_dump($value);

// The above is identical to this if/else statement
if(isset($x)){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Here is the table that explain the difference and similarity between '??' and ?:

这是解释‘?”和吗?

PHP三元运算符和空合并运算符。

Special Note : null coalescing operator and ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; and return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.

特别注意:空合并运算符和三元运算符是一个表达式,它不计算变量,而是表示表达式的结果。如果您想通过引用返回一个变量,这一点很重要。语句返回$foo ?美元的酒吧;返回$var = 42 ?a:b美元;因此,在引用返回函数中将不起作用,并发出警告。

#4


10  

Both of them behave differently when it comes to dynamic data handling.

当涉及到动态数据处理时,它们的行为都是不同的。

If the variable is empty ( '' ) the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.

如果变量为空("),空合并将把变量视为真,而速记三元运算符则不会。这是需要记住的。

$a = NULL;
$c = '';

print $a ?? '1b';
print "\n";

print $a ?: '2b';
print "\n";

print $c ?? '1d';
print "\n";

print $c ?: '2d';
print "\n";

print $e ?? '1f';
print "\n";

print $e ?: '2f';

And the output:

和输出:

1b
2b

2d
1f

Notice: Undefined variable: e in /in/ZBAa1 on line 21
2f

Link: https://3v4l.org/ZBAa1

链接:https://3v4l.org/ZBAa1

#5


6  

Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.

在php交互模式(终端上的php -a)上运行以下命令。每行的注释显示结果。

var_dump (false ?? 'value2');   # bool(false)
var_dump (true  ?? 'value2');   # bool(true)
var_dump (null  ?? 'value2');   # string(6) "value2"
var_dump (''    ?? 'value2');   # string(0) ""
var_dump (0     ?? 'value2');   # int(0)

var_dump (false ?: 'value2');   # string(6) "value2"
var_dump (true  ?: 'value2');   # bool(true)
var_dump (null  ?: 'value2');   # string(6) "value2"
var_dump (''    ?: 'value2');   # string(6) "value2"
var_dump (0     ?: 'value2');   # string(6) "value2"

So this is my interpretation:

1. The Null Coalescing Operator - ??:

  • ?? is like a "gate" that only lets NULL through.
  • ? ?就像一个只能让NULL通过的“门”。
  • So, it always returns first parameter, unless first parameter happens to be NULL.
  • 它总是返回第一个参数,除非第一个参数恰好为空。
  • This means ?? is same as ( !isset() || is_null() )
  • 这意味着?与(!isset() || is_null())相同

2. The Ternary Operator - ?:

  • ?: is like a gate that lets anything falsy through - including NULL
  • ?:就像一扇门,让任何虚假的东西通过——包括零
  • 0, empty string, NULL, false, !isset(), empty() .. anything that smells falsy
  • 0,空字符串,NULL, false, !isset(), empty() .任何气味falsy
  • Just like the classic ternary operator: echo ($x ? $x : false)
  • 就像经典的三元操作符:echo ($x ?$ x:假)
  • NOTE: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables
  • 注意:?:将在未定义(未设置或!isset())变量上抛出PHP通知

3. So doctor, when do I use ?? and ?: ..

  • I'm only joking - I'm not a doctor and this is just an interpretation
  • 我只是开玩笑——我不是医生,这只是一种解释
  • I would use ?: when
    • doing empty($x) checks
    • 做空($ x)检查
    • Classic ternary operation like !empty($x) ? $x : $y can be shortened to $x ?: $y
    • 经典的三元运算,比如!空($x) ?$x: $y可以缩短为$x: $y
    • if(!$x) { fn($x); } else { fn($y); } can be shortened to fn(($x ?: $y))
    • 如果(! $ x){ fn($ x);其他} { fn($ y);}可以缩写为fn($x ?: $y)
  • 我将使用?:当执行empty($x)检查经典的三元操作时,比如!empty($x) ?$x: $y可以缩写为$x ?: $y if(!$x) {fn($x);其他} { fn($ y);}可以缩写为fn($x ?: $y)
  • I would use ?? when
    • I want to do an !isset() || is_null() check
    • 我要做一个!isset() || is_null()检查
    • e.g check if an object exists - $object = $object ?? new objClassName();
    • e。检查对象是否存在- $object = $object ?新objClassName();
  • 我会用? ?当我要做!isset() || is_null()检查e。检查对象是否存在- $object = $object ?新objClassName();

4. Stacking operators ...

  1. Ternary Operator can be stacked ...

    三元算符可以叠加……

    echo 0 ?: 1 ?: 2 ?: 3; //1
    echo 1 ?: 0 ?: 3 ?: 2; //1
    echo 2 ?: 1 ?: 0 ?: 3; //2
    echo 3 ?: 2 ?: 1 ?: 0; //3
    
    echo 0 ?: 1 ?: 2 ?: 3; //1
    echo 0 ?: 0 ?: 2 ?: 3; //2
    echo 0 ?: 0 ?: 0 ?: 3; //3
    

    Source & credit for this code

    这段代码的来源和信用

    This is basically a sequence of:

    这基本上是一个序列:

    if( truthy ) {}
    else if(truthy ) {}
    else if(truthy ) {}
    ..
    else {}
    
  2. Null Coalese Operator can be stacked ...

    空聚类算子可以叠加…

    $v = $x ?? $y ?? $z; 
    

    This is a sequence of:

    这是一个序列:

    if(!isset($x) || is_null($x) ) {} 
    else if(!isset($y) || is_null($y) ) {}
    else {}
    
  3. Using stacking, I can shorten this:

    使用堆叠,我可以缩短这个:

    if(!isset($_GET['name'])){
       if(isset($user_name) && !empty($user_name)){
          $name = $user_name;
       }else {
          $name = 'anonymous';
       }
    } else { 
       $name = $_GET['name'];
    }
    

    To this:

    :

    $name = $_GET['name'] ?? $user_name ?: 'anonymous';
    

    Cool, right? :-)

    很酷,对吧?:-)

#6


3  

It seems there are pros and cons to using either ?? or ?:. The pro to using ?: is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ?? the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else.

这两种用法似乎都有优缺点。或:。它的值是否为false、null和“相同”。缺点是,如果前面的参数为空,它将报告一个E_NOTICE。用? ?pro是没有E_NOTICE,但坏处是它的值为false和null是不一样的。在我的经验中,我看到人们开始交替地使用null和false,但是他们最终会修改他们的代码,使之与使用null或false一致,但不是两者都使用。另一种选择是创建一个更复杂的三元条件:(isset($something)还是!$something) ?一些事情:something_else美元。

The following is an example of the difference of using the ?? operator using both null and false:

下面是使用?使用null和false的操作符:

$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---

$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---

By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:

然而,通过详细说明三元运算符,我们可以使一个假的或空的字符串“”表现为一个null,而不需要抛出e_notice:

$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---

Personally, I think it would be really nice if a future rev of PHP included another new operator: :? that replaced the above syntax. ie: // $var = $false :? "true"; That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...

我个人认为,如果未来的PHP rev包含另一个新的操作符::?这取代了上面的语法。ie: // $var = $false:?“真正的”;该语法将求出null、false和“”,而不抛出E_NOTICE…

#7


2  

Scroll down on this link and view the section, it gives you a comparative example as seen below:

向下滚动这个链接并查看部分,它给你一个对比的例子如下所示:

<?php
/** 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';

/** Coalescing can be chained: this will return the first defined value out of $_GET['user'], $_POST['user'], and 'nobody'. **/
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

However, it is not advised to chain the operators as it makes it harder to understand the code when reading it later on.

但是,不建议对操作符进行链接,因为这样会使以后读取代码时更难理解。

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

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

Essentially, using the coalescing operator will make it auto check for null unlike the ternary operator.

本质上,使用合并运算符将使它自动检查零,不像三元运算符。

#8


1  

class a
{
    public $a = 'aaa';
}

$a = new a();

echo $a->a;  // Writes 'aaa'
echo $a->b;  // Notice: Undefined property: a::$b

echo $a->a ?? '$a->a does not exists';  // Writes 'aaa'

// Does not throw an error although $a->b does not exist.
echo $a->b ?? '$a->b does not exist.';  // Writes $a->b does not exist.

// Does not throw an error although $a->b and also $a->b->c does not exist.
echo $a->b->c ?? '$a->b->c does not exist.';  // Writes $a->b->c does not exist.

#9


0  

Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

Null联合运算符只执行两个任务:它检查变量是否被设置,以及它是否为Null。请看下面的例子:

<?php
# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'

# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

# case 3:
unset($greeting);
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

上面的代码示例声明,Null联合运算符处理一个不存在的变量和一个以相同的方式设置为Null的变量。

Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

零合并算子是对三元算子的改进。看看下面比较这两个代码片段:

<?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.

So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

因此,两者之间的区别在于,Null联合运算符被设计成比三元运算符更好地处理未定义的变量。然而,三元运算符是if-else的简写。

Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.

空合并运算符并不意味着要替换三元运算符,但是在某些用例中,比如上面的示例,它允许您以更少的麻烦编写干净的代码。

Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples

学分:http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples

#1


132  

When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say:

当第一个参数为空时,它们基本上是相同的,只是当你有一个未定义的变量时,null合并不会输出一个E_NOTICE。PHP 7.0迁移文档中有如下内容:

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

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

Here's some example code to demonstrate this:

这里有一些示例代码来演示这一点:

<?php

$a = null;

print $a ?? 'b';
print "\n";

print $a ?: 'b';
print "\n";

print $c ?? 'a';
print "\n";

print $c ?: 'a';
print "\n";

$b = array('a' => null);

print $b['a'] ?? 'd';
print "\n";

print $b['a'] ?: 'd';
print "\n";

print $b['c'] ?? 'e';
print "\n";

print $b['c'] ?: 'e';
print "\n";

And it's output:

输出:

b
b
a

Notice: Undefined variable: c in /in/apAIb on line 14
a
d
d
e

Notice: Undefined index: c in /in/apAIb on line 33
e

The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.

有通知的行是我使用速记三元运算符而不是空合并运算符的行。但是,即使有通知,PHP也会返回相同的响应。

Execute the code: https://3v4l.org/McavC

执行代码:https://3v4l.org/McavC

Of course, this is always assuming the first argument is null. Once it's no longer null, then you end up with differences in that the ?? operator would always return the first argument while the ?: shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.

当然,它总是假设第一个参数为null。一旦它不再为空,那么你就会得到不同的值?操作符总是返回第一个参数,而?:速记只有在第一个参数是真实的情况下才会返回,这依赖于PHP如何将数据类型转换为布尔值。

So:

所以:

$a = false ?? 'f';
$b = false ?: 'g';

would then have $a be equal to false and $b equal to 'g'.

然后a = false b = g。

#2


36  

If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:

如果您使用这样的快捷三元运算符,如果$_GET['username']没有设置,将会引起通知:

$val = $_GET['username'] ?: 'default';

So instead you have to do something like this:

所以你必须做这样的事情:

$val = isset($_GET['username']) ? $_GET['username'] : 'default';

The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:

null coalescing运算符等价于上述语句,如果$_GET['username']未设置或为null,则返回'default':

$val = $_GET['username'] ?? 'default';

Note that it does not check truthiness. It checks only if it is set and not null.

注意,它不检查真实性。它只检查它是否被设置为非空。

You can also do this, and the first defined (set and not null) value will be returned:

您也可以这样做,第一个定义的(set和not null)值将返回:

$val = $input1 ?? $input2 ?? $input3 ?? 'default';

Now that is a proper coalescing operator.

这是一个合适的合并运算符。

#3


13  

The major difference is that

主要的区别在于

  1. Ternary Operator expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2) evaluates to expr1 if expr1 is not NULL

    三元运算符表达式expr1 ?: expr3返回expr1,如果expr1计算为TRUE,但另一方面,expr1是否为空?(expr2)如果expr1不是NULL,则计算为expr1

  2. Ternary Operator expr1 ?: expr3 emit a notice if the left-hand side value (expr1) does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2) In particular, does not emit a notice if the left-hand side value (expr1) does not exist, just like isset().

    三元运算符expr1 ?: expr3会发出通知,如果左边的值(expr1)不存在,但另一方面,零合并运算符(expr1) ?(expr2)特别地,如果不存在左侧值(expr1),则不会发出通知,就像isset()一样。

  3. TernaryOperator is left associative

    TernaryOperator剩下的联想

    ((true ? 'true' : false) ? 't' : 'f');
    

    Null Coalescing Operator is right associative

    空联合运算符是正确的联合运算符

    ($a ?? ($b ?? $c));
    

Now lets explain the difference between by example :

现在让我们通过例子来解释两者的区别:

Ternary Operator (?:)

三元操作符(?)

$x='';
$value=($x)?:'default';
var_dump($value);

// The above is identical to this if/else statement
if($x){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Null Coalescing Operator (??)

空合并操作符(? ?)

$value=($x)??'default';
var_dump($value);

// The above is identical to this if/else statement
if(isset($x)){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Here is the table that explain the difference and similarity between '??' and ?:

这是解释‘?”和吗?

PHP三元运算符和空合并运算符。

Special Note : null coalescing operator and ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; and return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.

特别注意:空合并运算符和三元运算符是一个表达式,它不计算变量,而是表示表达式的结果。如果您想通过引用返回一个变量,这一点很重要。语句返回$foo ?美元的酒吧;返回$var = 42 ?a:b美元;因此,在引用返回函数中将不起作用,并发出警告。

#4


10  

Both of them behave differently when it comes to dynamic data handling.

当涉及到动态数据处理时,它们的行为都是不同的。

If the variable is empty ( '' ) the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.

如果变量为空("),空合并将把变量视为真,而速记三元运算符则不会。这是需要记住的。

$a = NULL;
$c = '';

print $a ?? '1b';
print "\n";

print $a ?: '2b';
print "\n";

print $c ?? '1d';
print "\n";

print $c ?: '2d';
print "\n";

print $e ?? '1f';
print "\n";

print $e ?: '2f';

And the output:

和输出:

1b
2b

2d
1f

Notice: Undefined variable: e in /in/ZBAa1 on line 21
2f

Link: https://3v4l.org/ZBAa1

链接:https://3v4l.org/ZBAa1

#5


6  

Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.

在php交互模式(终端上的php -a)上运行以下命令。每行的注释显示结果。

var_dump (false ?? 'value2');   # bool(false)
var_dump (true  ?? 'value2');   # bool(true)
var_dump (null  ?? 'value2');   # string(6) "value2"
var_dump (''    ?? 'value2');   # string(0) ""
var_dump (0     ?? 'value2');   # int(0)

var_dump (false ?: 'value2');   # string(6) "value2"
var_dump (true  ?: 'value2');   # bool(true)
var_dump (null  ?: 'value2');   # string(6) "value2"
var_dump (''    ?: 'value2');   # string(6) "value2"
var_dump (0     ?: 'value2');   # string(6) "value2"

So this is my interpretation:

1. The Null Coalescing Operator - ??:

  • ?? is like a "gate" that only lets NULL through.
  • ? ?就像一个只能让NULL通过的“门”。
  • So, it always returns first parameter, unless first parameter happens to be NULL.
  • 它总是返回第一个参数,除非第一个参数恰好为空。
  • This means ?? is same as ( !isset() || is_null() )
  • 这意味着?与(!isset() || is_null())相同

2. The Ternary Operator - ?:

  • ?: is like a gate that lets anything falsy through - including NULL
  • ?:就像一扇门,让任何虚假的东西通过——包括零
  • 0, empty string, NULL, false, !isset(), empty() .. anything that smells falsy
  • 0,空字符串,NULL, false, !isset(), empty() .任何气味falsy
  • Just like the classic ternary operator: echo ($x ? $x : false)
  • 就像经典的三元操作符:echo ($x ?$ x:假)
  • NOTE: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables
  • 注意:?:将在未定义(未设置或!isset())变量上抛出PHP通知

3. So doctor, when do I use ?? and ?: ..

  • I'm only joking - I'm not a doctor and this is just an interpretation
  • 我只是开玩笑——我不是医生,这只是一种解释
  • I would use ?: when
    • doing empty($x) checks
    • 做空($ x)检查
    • Classic ternary operation like !empty($x) ? $x : $y can be shortened to $x ?: $y
    • 经典的三元运算,比如!空($x) ?$x: $y可以缩短为$x: $y
    • if(!$x) { fn($x); } else { fn($y); } can be shortened to fn(($x ?: $y))
    • 如果(! $ x){ fn($ x);其他} { fn($ y);}可以缩写为fn($x ?: $y)
  • 我将使用?:当执行empty($x)检查经典的三元操作时,比如!empty($x) ?$x: $y可以缩写为$x ?: $y if(!$x) {fn($x);其他} { fn($ y);}可以缩写为fn($x ?: $y)
  • I would use ?? when
    • I want to do an !isset() || is_null() check
    • 我要做一个!isset() || is_null()检查
    • e.g check if an object exists - $object = $object ?? new objClassName();
    • e。检查对象是否存在- $object = $object ?新objClassName();
  • 我会用? ?当我要做!isset() || is_null()检查e。检查对象是否存在- $object = $object ?新objClassName();

4. Stacking operators ...

  1. Ternary Operator can be stacked ...

    三元算符可以叠加……

    echo 0 ?: 1 ?: 2 ?: 3; //1
    echo 1 ?: 0 ?: 3 ?: 2; //1
    echo 2 ?: 1 ?: 0 ?: 3; //2
    echo 3 ?: 2 ?: 1 ?: 0; //3
    
    echo 0 ?: 1 ?: 2 ?: 3; //1
    echo 0 ?: 0 ?: 2 ?: 3; //2
    echo 0 ?: 0 ?: 0 ?: 3; //3
    

    Source & credit for this code

    这段代码的来源和信用

    This is basically a sequence of:

    这基本上是一个序列:

    if( truthy ) {}
    else if(truthy ) {}
    else if(truthy ) {}
    ..
    else {}
    
  2. Null Coalese Operator can be stacked ...

    空聚类算子可以叠加…

    $v = $x ?? $y ?? $z; 
    

    This is a sequence of:

    这是一个序列:

    if(!isset($x) || is_null($x) ) {} 
    else if(!isset($y) || is_null($y) ) {}
    else {}
    
  3. Using stacking, I can shorten this:

    使用堆叠,我可以缩短这个:

    if(!isset($_GET['name'])){
       if(isset($user_name) && !empty($user_name)){
          $name = $user_name;
       }else {
          $name = 'anonymous';
       }
    } else { 
       $name = $_GET['name'];
    }
    

    To this:

    :

    $name = $_GET['name'] ?? $user_name ?: 'anonymous';
    

    Cool, right? :-)

    很酷,对吧?:-)

#6


3  

It seems there are pros and cons to using either ?? or ?:. The pro to using ?: is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ?? the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else.

这两种用法似乎都有优缺点。或:。它的值是否为false、null和“相同”。缺点是,如果前面的参数为空,它将报告一个E_NOTICE。用? ?pro是没有E_NOTICE,但坏处是它的值为false和null是不一样的。在我的经验中,我看到人们开始交替地使用null和false,但是他们最终会修改他们的代码,使之与使用null或false一致,但不是两者都使用。另一种选择是创建一个更复杂的三元条件:(isset($something)还是!$something) ?一些事情:something_else美元。

The following is an example of the difference of using the ?? operator using both null and false:

下面是使用?使用null和false的操作符:

$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---

$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---

By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:

然而,通过详细说明三元运算符,我们可以使一个假的或空的字符串“”表现为一个null,而不需要抛出e_notice:

$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---

Personally, I think it would be really nice if a future rev of PHP included another new operator: :? that replaced the above syntax. ie: // $var = $false :? "true"; That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...

我个人认为,如果未来的PHP rev包含另一个新的操作符::?这取代了上面的语法。ie: // $var = $false:?“真正的”;该语法将求出null、false和“”,而不抛出E_NOTICE…

#7


2  

Scroll down on this link and view the section, it gives you a comparative example as seen below:

向下滚动这个链接并查看部分,它给你一个对比的例子如下所示:

<?php
/** 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';

/** Coalescing can be chained: this will return the first defined value out of $_GET['user'], $_POST['user'], and 'nobody'. **/
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

However, it is not advised to chain the operators as it makes it harder to understand the code when reading it later on.

但是,不建议对操作符进行链接,因为这样会使以后读取代码时更难理解。

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

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

Essentially, using the coalescing operator will make it auto check for null unlike the ternary operator.

本质上,使用合并运算符将使它自动检查零,不像三元运算符。

#8


1  

class a
{
    public $a = 'aaa';
}

$a = new a();

echo $a->a;  // Writes 'aaa'
echo $a->b;  // Notice: Undefined property: a::$b

echo $a->a ?? '$a->a does not exists';  // Writes 'aaa'

// Does not throw an error although $a->b does not exist.
echo $a->b ?? '$a->b does not exist.';  // Writes $a->b does not exist.

// Does not throw an error although $a->b and also $a->b->c does not exist.
echo $a->b->c ?? '$a->b->c does not exist.';  // Writes $a->b->c does not exist.

#9


0  

Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

Null联合运算符只执行两个任务:它检查变量是否被设置,以及它是否为Null。请看下面的例子:

<?php
# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'

# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

# case 3:
unset($greeting);
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

上面的代码示例声明,Null联合运算符处理一个不存在的变量和一个以相同的方式设置为Null的变量。

Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

零合并算子是对三元算子的改进。看看下面比较这两个代码片段:

<?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.

So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

因此,两者之间的区别在于,Null联合运算符被设计成比三元运算符更好地处理未定义的变量。然而,三元运算符是if-else的简写。

Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.

空合并运算符并不意味着要替换三元运算符,但是在某些用例中,比如上面的示例,它允许您以更少的麻烦编写干净的代码。

Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples

学分:http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples