【发布时间】:2017-10-06 10:31:38
【问题描述】:
我总是发现自己在写这样的东西:
if(isset($var))
{
DoSomethingWith($var);
}
else
{
DoSomethingWith(null);
}
或
if(isset($arr["key"]))
{
DoSomethingWith($arr["key"];
}
else
{
DoSomethingWith(null);
}
我的问题是这样的:
有没有办法写一个get_var_if_set()函数,这样你就可以简单的写...
DoSomethingWith(get_var_if_set($var));
/// and
DoSomethingWith(get_var_if_set($arr["key"]));
....如果 $var 不存在或 $arr 没有“key”的设置值,则不通知?
我想应该是这样的:
function get_var_if_set($a)
{
return (isset($a) ? $a : null);
}
但这不起作用,因为使用未设置的变量调用 get_var_if_set() 总是会生成一个通知,所以它可能需要一点魔法。
谢谢大家。
编辑 删除答案的用户建议通过引用传递变量,因为如果 $variable 不存在,PHP 将传递 null。
那就完美了,看看这些解决方案(可能是equivalent):
function get_var_if_set(&$a) { return (isset($a) ? $a : null); }
function get_var_if_set(&$a) { return $a ?? null; } // Only in PHP 7.0+ (Coalescing operator)
注意:Koray Küpe建议的合并运算符
问题as you can see 是他们在return 语句中以某种方式初始化传递的变量。 我们不希望这样。
【问题讨论】:
-
在新文档中,比较
echo $a;与echo @$a;。虽然我认为抑制错误通常根本不是一件好事。 -
您可以简单地使用:
DoSomethingWith($var??null);或DoSomethingWith($var?:null); -
@LucasKrupinski
@在变量前面有什么用? -
@AntonisTsimourtos -
@suppresses errors -
@AntonisTsimourtos 它用于抑制错误和警告
标签: php function isset unset notice