When I use a variable in PHP which does not exist , I will get a warning/error message.
Notice: Undefined variable
So usually I'm writing an if-statement to initialize it first.
Example 1:
if (!isset($MySpecialVariable))
{
$MySpecialVariable = 0;
}
$MySpecialVariable++;
Example 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.
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
). 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
Value=8
a exists
b exists
Value=ValueForB
b exists
c NotSet
Value=StandardValue3
c exists
d exists
Value=ValueForD
d exists
When you are running PHP7 you can use the null coalescing operator
Like:
$myVar = $myVar ?? 0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.