Right now my pages look something like this:
if($_GET[\'something\'] == \'somevalue\')
{
$output .= \'somecode\';
// make a DB query, fetch a row
This is much more elegant and readable.
try
{
if($_GET['something'] != 'somevalue')
{
throw new Exception ('something is not a valid value');
}
$output .= 'somecode';
// make a DB query, fetch a row
//...
$row = $stmt->Fetch(PDO::ASSOC);
if($row == null)
{
throw new Exception ('the row does not exist.');
}
$output .= 'morecode';
if(somethingIsOK())
{
$output .= 'yet more page output';
}
else
{
throw new Exception ('something is most definitely not OK.');
}
echo $output;
}
catch (Exception $e)
{
echo $e->getMessage();
}
PHP has a built in class, ErrorException, for translating PHP errors into exceptions, which if unhandled, would naturally stop execution.
Exceptions have improved error handling mechanisms (try catch) and better debugging information (stack traces).
Include this at the top most of your execution path (the config, or something which is included first with all your code):
set_error_handler(function($nNumber, $strMessage, $strFilePath, $nLineNumber){
throw new \ErrorException($strMessage, 0, $nNumber, $strFilePath, $nLineNumber);
}, /*E_ALL*/ -1);
Although PDO supports throwing exceptions, it is off by default, you have to enable it:
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
If using MySQL, you also want an error for not setting mandatory fields and many other errors/warnings forgiven by default:
$pdo->exec("SET sql_mode = 'STRICT_ALL_TABLES'");
Exceptions can be handled like in many other programming languages using try catch finally:
try
{
echo $iAmAnUndefinedVariable;
}
catch(\Throwable $exception)
{
/*[...]*/
}
When validating stuff, just throw exceptions: throw new Exception("Missing URL variable userId!");
It would be nice if PHP made a clean break someday from the legacy error reporting thing and just throw exceptions by default (deprecate error_reporting() and change the default).