dpp*_*dpp 49 php ternary-operator null-coalescing-operator php-7
在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';
Run Code Online (Sandbox Code Playgroud)
zer*_*kms 63
PHP 7添加了null coalesce运算符:
// 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';
Run Code Online (Sandbox Code Playgroud)
您还可以看一下编写php的三元运算符的简短方法吗?:( 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';
Run Code Online (Sandbox Code Playgroud)
你与C#的比较是不公平的."在PHP中你必须做类似的事情" - 在C#中,如果你试图访问一个不存在的数组/字典项,你也会遇到运行时错误.
koj*_*iro 51
该空联合运营商,( ??)已接受并执行PHP 7.它与短三元运算符(?:)的不同之处在于??它将抑制E_NOTICE在尝试访问没有键的数组时发生的情况.RFC中的第一个示例给出:
$username = $_GET['user'] ?? 'nobody';
// equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
Run Code Online (Sandbox Code Playgroud)
请注意,??操作员不需要手动应用isset来防止E_NOTICE.
Luk*_*Led 10
我用的是功能.显然它不是运营商,但似乎比你的方法更清洁:
function isset_or(&$check, $alternate = NULL)
{
return (isset($check)) ? $check : $alternate;
}
Run Code Online (Sandbox Code Playgroud)
用法:
isset_or($_REQUEST['test'],'hi');
Run Code Online (Sandbox Code Playgroud)
在PHP 7之前,没有.如果需要涉及isset,使用的模式是isset($var) ? $var : null.没有?:包含其特征的运营商isset.
| 归档时间: |
|
| 查看次数: |
13836 次 |
| 最近记录: |