Home > database >  Muting / ignoring PHP Notices from a part of my code
Muting / ignoring PHP Notices from a part of my code

Time:01-30

I have some code in my WordPress project, that fills up my debug.log-file with garbage. I'm trying to figure out why this is, and it might be something related to the WordPress Core (that is called by my code, none-the-less).

Is there a way, where I can tell PHP to ignore notices for a specific part of my code?

Example

// Imagine, that I'm not sure, if $some_obj->ID exists
// And that $some_obj is passed by some other code, that I don't control
function my_shady_function( $some_obj ){

  $numbers = [ '4', '8', '15', '16', '23', '42' ];  

  if ( in_array( $some_obj->ID, $numbers ) ) { // Mute notices here (ID not set on obj)
    return true;
  }

  $new_obj = new stdObject(); // Forgetting to set property is_true
  if ( $new_obj->is_true ) { // But I'd like notices here!
    return true;
  }
}

CodePudding user response:

One way would be to change error_reporting before and after code where I don't want to see notices

Inspired by this post, setting error_reporting in the code I figured I could do this:

function my_shady_function( $some_obj ){

  $original_error_reporting = error_reporting();
  error_reporting( $original_error_reporting & ~E_NOTICE);
  $numbers = [ '4', '8', '15', '16', '23', '42' ];  
  if ( in_array( $some_obj->ID, $numbers ) ) { // Mute notices here (ID not set on obj)
    return true;
  }
  error_reporting( $original_error_reporting );

  $new_obj = new stdObject(); // Forgetting to set property is_true
  if ( $new_obj->is_true ) { // But I'd like notices here!
    return true;
  }
}

I'm not sure, if this is the best way to go.

CodePudding user response:

I think the best way is to check $some_obj->ID like is_int() or something else depend on this variable.

if(is_int($some_obj->ID) && in_array($some_obj->ID, $numbers)) {

in this case, in_array will not executed, when is_int is false.

  •  Tags:  
  • Related