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#中,如果您尝试访问不存在的数组/字典项,那么还将出现运行时错误。