PHP中C#的空合并运算符(??) [英] C#'s null coalescing operator (??) in PHP

查看:97
本文介绍了PHP中C#的空合并运算符(??)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否存在像C#的??一样的三元运算符?

Is there a ternary operator or the like in PHP that acts like ?? of C#?

??简洁明了,但是在PHP中,您必须执行以下操作:

?? in C# is clean and shorter, but in PHP you have to do something like:

// This is absolutely okay except that $_REQUEST['test'] is kind of redundant.
echo isset($_REQUEST['test'])? $_REQUEST['test'] : 'hi';

// This is perfect! Shorter and cleaner, but only in this situation.
echo null? : 'replacement if empty';

// This line gives error when $_REQUEST['test'] is NOT set.
echo $_REQUEST['test']?: 'hi';

推荐答案

PHP 7添加了您还可以查看编写PHP三元运算符的简短方法?:(仅PHP> = 5.3)

You could also look at short way of writing PHP's ternary operator ?: (PHP >=5.3 only)

// Example usage for: Short Ternary Operator
$action = $_POST['action'] ?: 'default';

// The above is identical to
$action = $_POST['action'] ? $_POST['action'] : 'default';

与C#的比较是不公平的. 在PHP中,您必须执行类似的操作"-在C#中,如果您尝试访问不存在的数组/字典项,也会遇到运行时错误.

And your comparison to C# is not fair. "in PHP you have to do something like" - In C# you will also have a runtime error if you try to access a non-existent array/dictionary item.

这篇关于PHP中C#的空合并运算符(??)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆