Php function argument error suppression, empty() i

2020-03-13 05:49发布

I'm pretty sure the answer to this question is no, but in case there's some PHP guru

is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of '@'

Much like empty and isset do. You can pass in a variable you just made up and it won't error.

ex:

empty($someBogusVar); // no error

myHappyFunction($someBogusVar); // Php warning / notice

14条回答
来,给爷笑一个
2楼-- · 2020-03-13 06:42

While the answer to the original question is "no", there is an options no one has mentioned.

When you use the @ sign, all PHP is doing is overriding the error_reporting level and temporarily setting it to zero. You can use "ini_restore('error_reporting');" to set it back to whatever it was before the @ was used.

This was useful to me in the situation where I wanted to write a convenience function to check and see if a variable was set, and had some other properties as well, otherwise, return a default value. But, sending an unset variable through caused a PHP notice, so I used the @ to suppress that, but then set error_reporting back to the original value inside the function.

Something like:

$var = @foo($bar);

function foo($test_var)
{
     ini_restore('error_reporting');

     if(is_set($test_var) && strlen($test_var))
     {
          return $test_var;
     }
     else
     {
          return -1;
     }
}

So, in the case above, if $bar is not set, I won't get an error when I call foo() with a non-existent variable. However, I will get an error from within the function where I mistakenly typed is_set instead of isset.

This could be a useful option covering what the original question was asking in spirit, if not in actual fact.

查看更多
Summer. ? 凉城
3楼-- · 2020-03-13 06:43

Summing up, the proper answer is no, you shouldn't (see caveat below).

There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want.

Summarizing an interesting comment discussion with Gerry: Passing the variable by reference is indeed valid if you check for the value of the variable inside the function and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to).

查看更多
登录 后发表回答