Passing unset variables to functions

可紊 提交于 2020-01-23 01:14:46

问题


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.
  1. When a variable doesn't exist and is passed to the function (suppressing the error) what is actually passed?
  2. Is there any undefined behaviour that this function could exhibit?
  3. Is there a better way of wrapping the testing for variable existence and supplying a default value from a function?
  4. 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:


  1. NULL is passed, notice error is raised.
  2. No, function sees only it's parameters (it doesn't care how it is being called)
  3. You can specify default value easily - function func($mandatory, $optional = 'default value');
  4. Isset withing a function on its parameters is pointless, because the parameters are already set in the functions signature.



回答2:


  1. null will be passed
  2. There is no undefined behaviour in PHP AFAIK
  3. Usually testing is done with empty($var), e.g.: Check(empty($foo) ? null : $foo), although depending on the circumstances isset may be more appropriate
  4. What isset does is exactly documented -- it tests if there is such a variable in scope and its value is not identical to null



回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!