请问 !empty($a) ? $a : $b 和 $a ?: $b 有什么区别

通过PHP代码运行比较一些特殊值(0,null 等),我发现 empty($a) 似乎与 !$a 没有区别,那么我在尝试寻找这类替换的 case 的时候,为什么从来都没有人提过

!empty($a) ? $a : $b
等于
$a ?: $b

是我遗漏了什么吗?

最佳答案

!empty($arr['key1']) 会先判断 isset(),如果 !$arr['key1'] 的话会尝试访问不存在的变量,产生警告,如下语句可以证明:

# 不会警告
$ php -r "!empty($arr['key1']);"
# 警告
$ php -r "!$arr['key1'];"                                           
PHP Notice:  Undefined variable: arr in Command line code on line 1 
PHP Stack trace:                                                    
PHP   1. {main}() Command line code:0                               

Notice: Undefined variable: arr in Command line code on line 1      

Call Stack:                                                         
    0.0005     366416   1. {main}() Command line code:0             
# 同警告
$ php -r "$arr['key1']?:'111';"
PHP Notice:  Undefined variable: arr in Command line code on line 1
PHP Stack trace:
PHP   1. {main}() Command line code:0

Notice: Undefined variable: arr in Command line code on line 1

Call Stack:
    0.0003     366536   1. {main}() Command line code:0
3年前 评论
讨论数量: 1

!empty($arr['key1']) 会先判断 isset(),如果 !$arr['key1'] 的话会尝试访问不存在的变量,产生警告,如下语句可以证明:

# 不会警告
$ php -r "!empty($arr['key1']);"
# 警告
$ php -r "!$arr['key1'];"                                           
PHP Notice:  Undefined variable: arr in Command line code on line 1 
PHP Stack trace:                                                    
PHP   1. {main}() Command line code:0                               

Notice: Undefined variable: arr in Command line code on line 1      

Call Stack:                                                         
    0.0005     366416   1. {main}() Command line code:0             
# 同警告
$ php -r "$arr['key1']?:'111';"
PHP Notice:  Undefined variable: arr in Command line code on line 1
PHP Stack trace:
PHP   1. {main}() Command line code:0

Notice: Undefined variable: arr in Command line code on line 1

Call Stack:
    0.0003     366536   1. {main}() Command line code:0
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!