Passing unset variables to functions

本小妞迷上赌 提交于 2019-12-04 10:13:50
  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.
  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

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.

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