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

后端 未结 14 723
执笔经年
执笔经年 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.

提交回复
热议问题