当我在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 NotSet 值= StandardValue3 c存在 d存在 值= ValueForD d存在
当您运行PHP7时,您可以使用null coalescing operator 喜欢:
$myVar = $myVar ?? 0;