Php function argument error suppression, empty() isset() emulation

后端 未结 14 526
执笔经年
执笔经年 2021-01-11 17:32

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 exi

相关标签:
14条回答
  • 2021-01-11 18:30

    You can do this using func_get_args like so:

    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    function defaultValue() {
        $args = func_get_args();
    
        foreach($args as $arg) {
            if (!is_array($arg)) {
                $arg = array($arg);
            }
            foreach($arg as $a) {
                if(!empty($a)) {
                    return $a;
                }
            }
        }
    
        return false;
    }
    
    $var = 'bob';
    
    echo defaultValue(compact('var'), 'alpha') . "\n"; //returns 'bob'
    echo defaultValue(compact('var2'), 'alpha') . "\n"; //returns 'alpha'
    echo defaultValue('alpha') . "\n"; //return
    echo defaultValue() . "\n";
    

    This func goes one step further and would give you the first non empty value of any number of args (you could always force it to only take up to two args but this look more useful to me like this).

    EDIT: original version didn't use compact to try and make an array of args and STILL gave an error. Error reporting bumped up a notch and this new version with compact is a little less tidy, but still does the same thing and allows you to provide a default value for non existent vars.

    0 讨论(0)
  • 2021-01-11 18:32

    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).

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