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添加了空合并运算符:
// 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#中,如果你尝试访问一个不存在的数组/字典项目,你也会遇到运行时错误。
空合并运算符( ??
)已被接受并在PHP 7中实现。它与短三元运算符( ?:
:)的区别在于??
会压制E_NOTICE
,当试图访问一个没有密钥的数组时,会发生这种情况。 RFC中的第一个例子给出了:
$username = $_GET['user'] ?? 'nobody';
// equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
注意到??
操作员不需要手动应用isset
来阻止E_NOTICE
。
我使用功能。 显然它不是操作员,但看起来比你的方法更清洁:
function isset_or(&$check, $alternate = NULL)
{
return (isset($check)) ? $check : $alternate;
}
用法:
isset_or($_REQUEST['test'],'hi');
链接地址: http://www.djcxy.com/p/1739.html