How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

前端 未结 3 1046
轻奢々
轻奢々 2021-01-26 10:53

When E_NOTICE is set to on, PHP will report undefined index for arrays. I want to suppress this error for $_GET only. Is there any way to do that other than prepend

相关标签:
3条回答
  • 2021-01-26 11:13

    The best method is to check for the existence of the array key before you use it each time, using isset.

    So instead of

    $cow=(int)$_GET['cow'];
    

    do

    if(isset($_GET['cow'])){ $cow=(int)$_GET['cow']; }
    

    That's verbose, however. So, you can wrap this in a function such as

    function get($key_name){
      return isset($_GET[$key_name])?$_GET[$key_name]:null;
      }
    

    and then,

    $cow=get('cow');
    
    0 讨论(0)
  • 2021-01-26 11:19

    If you don't want to modify all the $_GET references in your code, you could create your own error handler to PHP, by using set_error_handler function

    Example (completely untested, but shows the idea):

    function myErrHandler ($errno, $errstr, $errfile, $errline) {
        if(strstr("GET", $errstr)) {
            // suppress message
            return true;
        }
    
        // otherwise, continue with PHP internal error handler
        return false;
    }
    
    set_error_handler("myErrHandler", E_NOTICE);
    
    0 讨论(0)
  • 2021-01-26 11:22

    The proper solution is to use something like isset or array_key_exists first, thus making sure your code successfully handles things when the array index is outright missing, as opposed to '' or zero:

    $foo = array_key_exists('foo', $_GET) ? $_GET['foo'] : 'Whoops!';
    
    0 讨论(0)
提交回复
热议问题