PHP中的C#的空合并运算符(??)
发布时间:2020-12-13 21:28:37 所属栏目:PHP教程 来源:网络整理
导读:在 PHP中是否有一个三元运算符或类似的东西? C#? ??在C#中是干净和短,但在PHP中,你必须做的事情如下: // This is absolutely okay except that $_REQUEST['test'] is kind of redundant.echo isset($_REQUEST['test'])? $_REQUEST['test'] : 'hi';// This
在
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#中,如果你试图访问一个不存在的数组/字典项,你也会遇到运行时错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |