简体   繁体   English

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

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

When I use a variable in PHP which does not exist , I will get a warning/error message. 当我在PHP中使用一个不存在变量时,会收到警告/错误消息。

Notice: Undefined variable 注意:未定义的变量


So usually I'm writing an if-statement to initialize it first. 所以通常我会先写一个if语句来初始化它。

Example 1: 范例1:

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

Example 2: 范例2:

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

The disadvantage is that I have to write $MySpecialVariable or $MyArray["MySpecialIndex"] several times and the program gets bloated. 缺点是我必须多次写入$MySpecialVariable$MyArray["MySpecialIndex"] ,程序变得肿。

How can I achieve the same result with writing the variable only once ? 如何只写一次变量就能达到相同的结果?

I'm looking for something like 我正在寻找类似的东西

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;
}

The key is to to pass the requested variable by reference ( &$MyVar ). 关键是通过引用( &$MyVar )传递请求的变量。 Otherwise it is not possible to call a function with a possibly uninitialized variable. 否则,将无法使用可能未初始化的变量来调用函数。

Test code: 测试代码:

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>";

Output: 输出:

a NotSet 一个NotSet
Value=8 值= 8
a exists 存在

b exists b存在
Value=ValueForB 值= ValueForB
b exists b存在

c NotSet c未设定
Value=StandardValue3 值= StandardValue3
c exists c存在

d exists d存在
Value=ValueForD 值= ValueForD
d exists d存在

When you are running PHP7 you can use the null coalescing operator 当您运行PHP7时,可以使用null合并运算符
Like: 喜欢:

$myVar = $myVar ?? 0;

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

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