How do I pass undefined vars to functions without E_NOTICE errors?

前端 未结 4 1766
深忆病人
深忆病人 2020-12-20 12:48

Pretty simple question really, how do I pass undefined vars to functions without E_NOTICE errors?

When passing undefined variables to functions such as isset(), no e

相关标签:
4条回答
  • 2020-12-20 12:59

    You have three options:

    • Use isset to handle the logic properly (isset($x) || isset($y) || isset($z))
    • Wrap everything in isset() and then have your function check if any of the arguements are true (kind of bleh)
    • Use @ to suppress errors (also bleh)

    An example of @ would be:

    function a($a) { } a(@$x);
    

    You should remember though that notices exist for a reason. I avoid error suppressing. It seems hacky to me. I would just properly wrap everything in isset(). It's a lot more verbose, but also, in my opinion anyway, more correct.

    0 讨论(0)
  • 2020-12-20 13:10

    Pass by reference will work for defined arguments.

    function my_isset(&$k) { ... }
    
    $bool = my_isset($_POST['hi']);
    
    0 讨论(0)
  • 2020-12-20 13:15

    Maybe something like this will work for you? It's a little bit hackish, but I think what you want is not quite possible without lazy evaluation of function arguments.

    if (atLeastOneIsSet($myArray, 1, 3, 4, 6)) doSomething();
    
    function atLeastOneIsSet(array $arr) {
        $args = func_get_args();
        for ($i = 1; $i < func_num_args(); ++$i)
            if (isset($arr[$args[$i]])) return true;
        return false;
    }
    

    Edit: oops, logic issues.

    0 讨论(0)
  • 2020-12-20 13:18

    isset is a bit special as it is actually a PHP language construct rather than a function [1].

    If a variable is undefined, you can't really pass it because it isn't defined (hence the warning).

    As stated in comments, you can suppress the warnings by prepending an @ to the variable which will prevent a warning from being emitted if it is not set. Then within the function you can check to see if the value is null or try using isset to see if it is registered.

    0 讨论(0)
提交回复
热议问题