gpt4 book ai didi

php - PHP 中 C# 的空值合并运算符 (??)

转载 作者:IT王子 更新时间:2023-10-29 00:42:24 25 4
gpt4 key购买 nike

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 coalescing 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# 中,如果你尝试访问不存在的数组/字典项,你也会遇到运行时错误。

关于php - PHP 中 C# 的空值合并运算符 (??),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7278835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com