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

后端 未结 14 722
执笔经年
执笔经年 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:09

    No, because this isn't really anything to do with the function; the error is coming from attempting to de-reference a non-existent array key. You can change the warning level of your PHP setup to surpress these errors, but you're better off just not doing this.

    Having said that, you could do something like

    function safeLookup($array, $key)
    {
      if (isset($array, $key))
        return $array[$key];
    
      return 0;
    }
    

    And use it in place of array key lookup

    defaultValue(safeLookup($foo, "bar"), "baz);
    

    Now I need to take a shower :)

提交回复
热议问题