【问题标题】:PHP - Is there a way to get a variable value if it is set?PHP - 如果设置了变量值,有没有办法获取它?
【发布时间】: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


【解决方案1】:

如果您使用 PHP 7.0+,则可以使用空合并运算符。

return $a ?? null;

注意:运算符检查变量是否存在且不为空。因此,如果变量已经设置但为空,它会返回 null 变量。

【讨论】:

  • 这很聪明,但是it does spit out notifications!问题是当你执行 call_a_function_with($some_unexistent_parameter); PHP 会生气。我想要一个“神奇的函数”,它告诉 PHP “我传递了什么,也不管它是否存在,我都是为处理未定义的索引和未知变量而构建的。”
【解决方案2】:

问题不在于var本身,而在于数组key的key在这个:

DoSomethingWith(get_var_if_set($arr["key"]))

因此,唯一的解决方案是检查数组和您要查找的密钥。

function get_var_if_set($a, $key = null)
{
    if(is_array($a) && array_key_exists($key, $array)) {
        return $a[$key]; 
    } else {
          return (isset($a) ? $a : null);
    }
}

【讨论】:

  • 函数isset()的酷处在于你可以给它一些不存在的东西,最多你会得到false; PHP 知道 isset() 可能会收到不存在的变量,但它不会通知它。我想要 isset 的某种包装函数,它直接为您提供 [value 或 null],而不是 [true 或 false]。您的解决方案忽略了如果您调用 get_var_if_set($inexistent_var),PHP 会告诉您(带有通知)$inexistent_var 不存在的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-17
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 2011-05-29
  • 2021-01-29
相关资源
最近更新 更多