繁体   English   中英

PHP替代if(!isset(…)){…} => GetVar($ Variable,$ ValueIfNotExists)

[英]PHP Alternative to if (!isset(…)) {…} => GetVar($Variable, $ValueIfNotExists)

当我在PHP中使用一个不存在变量时,会收到警告/错误消息。

注意:未定义的变量


所以通常我会先写一个if语句来初始化它。

范例1:

if (!isset($MySpecialVariable))
{
  $MySpecialVariable = 0;
}
$MySpecialVariable++;

范例2:

if (!isset($MyArray["MySpecialIndex"]))
{
  $MyArray["MySpecialIndex"] = "InitialValue";
}
$Value = $MyArray["MySpecialIndex"];

缺点是我必须多次写入$MySpecialVariable$MyArray["MySpecialIndex"] ,程序变得肿。

如何只写一次变量就能达到相同的结果?

我正在寻找类似的东西

GetVar($MySpecialVariable, 0); # Sets MySpecialVariable to 0 only if not isset()
$MySpecialVariable++;

$Value = GetVar($MyArray["MySpecialIndex"], "InitialValue");
function GetVar(&$MyVar, $ValueIfVarIsNotSet)
{
    $MyVar = (isset($MyVar)) ? $MyVar : $ValueIfVarIsNotSet;
    return $MyVar;
}

关键是通过引用( &$MyVar )传递请求的变量。 否则,将无法使用可能未初始化的变量来调用函数。

测试代码:

echo "<pre>";

unset($a);
$b = "ValueForB";
unset($c);
$d = "ValueForD";

echo (isset($a)) ? "a exists" : "a NotSet";
$a = GetVar($a, 7); # $a can be passed even if it is not set here
$a++;
echo "\nValue=$a\n";
echo (isset($a)) ? "a exists" : "a NotSet";
echo "\n\n";

echo (isset($b)) ? "b exists" : "b NotSet";
echo "\nValue=".GetVar($b, "StandardValue2")."\n";
echo (isset($b)) ? "b exists" : "b NotSet";
echo "\n\n";

echo (isset($c)) ? "c exists" : "c NotSet";
echo "\nValue=".GetVar($c, "StandardValue3")."\n";
echo (isset($a)) ? "c exists" : "c NotSet";
echo "\n\n";

echo (isset($d)) ? "d exists" : "d NotSet";
echo "\nValue=".GetVar($d, "StandardValue4")."\n";
echo (isset($d)) ? "d exists" : "d NotSet";
echo "\n\n";

echo "</pre>";

输出:

一个NotSet
值= 8
存在

b存在
值= ValueForB
b存在

c未设定
值= StandardValue3
c存在

d存在
值= ValueForD
d存在

当您运行PHP7时,可以使用null合并运算符
喜欢:

$myVar = $myVar ?? 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM