PHP中的C#的空合并运算符(??)
作者:互联网
在PHP中是否有一个三元运算符或类似的东西? C#?
??在C#中是干净和短,但在PHP中,你必须做的事情如下:
// 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添加了null coalesce operator:
// 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';
您还可以查看编写php的三元运算符?:的简短方法(仅限php> = 5.3)
// Example usage for: Short Ternary Operator
$action = $_POST['action'] ?: 'default';
// The above is identical to
$action = $_POST['action'] ? $_POST['action'] : 'default';
你与C#的比较是不公平的. “在PHP中你必须做类似的事情” – 在C#中,如果你试图访问一个不存在的数组/字典项,你也会遇到运行时错误.
标签:null-coalescing-operator,php,php-7,ternary-operator 来源: https://codeday.me/bug/20190919/1812013.html