【发布时间】:2011-11-08 21:07:46
【问题描述】:
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';
【问题讨论】:
-
?:非常接近??。事实上,?:实际上比??捕获更多类似空的情况;??专门用于null和!Nullabe<T>.HasValue。您听起来像是在寻找更像 JavaScript 的||运算符的东西。就像?:,但 JavaScript 不会抱怨引用未定义的键/成员——尽管如果您尝试引用未定义/空的键/成员,它会抛出错误,因此您只能进入一级。跨度> -
@dpp,你为什么说
someres然后改成test? -
查看第 7 版。我们终于有了。
-
PHP 7 有这个功能。请查看wiki.php.net/rfc/isset_ternary
-
如前所述,这将出现在 PHP 7 中。在早期版本中,我认为这是错误抑制运算符的少数有效用例之一,例如
echo @$_REQUEST['someres'] ?: 'hi';抑制错误。
标签: php ternary-operator null-coalescing-operator php-7