PHP Function of the Day (2011-9-29): trigger_error

[fphp]trigger_error[/fphp] creates an error message with an associated code. Depending on the code used the error can bring the program to a halt or simply get caught by the error handling in place.

While using try/catch and throw with exceptions has largely eclipsed trigger error in many PHP libraries it still has it’s place. The most important difference is that if an error is caught and handled code will resume after the point in the code trigger_error was called. Exceptions do not behave this way - when a throw occurs the remaining code in that scope will not execute, and neither will any other code above it as the exception bubbles outward.

Trigger Error can be used to notify you of troublesome but not necessarily fatal conditions. The most common is illegal property access on objects.


public function __get( $var ) {
  if (isset($this->$var)) {
    return $this->$var;
  } else {
    trigger_error("Classname::__get  {$var} does not exist", E_USER_NOTICE);
  }
}

It is ultimately up to you as program designer as to how much tolerance you want your code to have for this sort of thing. I consider it notice level stuff - I log these errors with an error catching routine and then append them to the outgoing HTML using a javascript snippet so that they are displayed in the browser’s debug console.