问题
My code:
function Check($Variable, $DefaultValue) {
if(isset($Variable) && $Variable != "" && $Variable != NULL) {
return $Variable;
}
else {
return $DefaultValue;
}
}
$a = Check(@$foo, false);
$b = Check(@$bar, "Hello");
//$a now equals false because $foo was not set.
//$b now equals "Hello" because $bar was not set.
- When a variable doesn't exist and is passed to the function (suppressing the error) what is actually passed?
- Is there any undefined behaviour that this function could exhibit?
- Is there a better way of wrapping the testing for variable existence and supplying a default value from a function?
- What does
isset()
check under the hood when testing a variable?
EDIT:
The default value is there to be user defined. Sometimes it will be a number, sometimes a string.
回答1:
- NULL is passed, notice error is raised.
- No, function sees only it's parameters (it doesn't care how it is being called)
- You can specify default value easily - function func($mandatory, $optional = 'default value');
- Isset withing a function on its parameters is pointless, because the parameters are already set in the functions signature.
回答2:
null
will be passed- There is no undefined behaviour in PHP AFAIK
- Usually testing is done with
empty($var)
, e.g.:Check(empty($foo) ? null : $foo)
, although depending on the circumstancesisset
may be more appropriate - What
isset
does is exactly documented -- it tests if there is such a variable in scope and its value is not identical tonull
回答3:
When a variable doesn't exist and is passed to the function (suppressing the error) what is actually passed?
In this case, you try to read from a non-existent variable
So, you get null
-- which is passed to the function.
Is there any undefined behaviour that this function could exhibit?
Not that I see -- except using the @
operator is not quite a good practice.
回答4:
You can pass the variable to the method by reference by putting an & in front of it when declaring the function. Then you can just check if it set inside the function and not have to worry about suppressing warnings when passing the value that isn't set.
function Check(&$Variable, $DefaultValue) {
if(isset($Variable) && $Variable != "" && $Variable != NULL) {
return $Variable;
}
else {
return $DefaultValue;
}
}
$a = Check($foo, false);
$b = Check($bar, "Hello");
来源:https://stackoverflow.com/questions/5551491/passing-unset-variables-to-functions