Safe PHP – Built-In Functions Rewritten to Throw Exceptions
Published on by Paul Redmond
In the project Safe PHP by David Négrier, all PHP functions that return false
are rewritten to throw exceptions instead.
The readme describes the problem with functions returning false
before exception handling came to PHP:
Most PHP core functions have been written before exception handling was added to the language. Therefore, most PHP functions do not throw exceptions. Instead, they return false in case of error.
The readme further goes on to explain what the code would look like to check for false
using the current language capabilities:
$content = file_get_contents('foobar.json');if ($content === false) { throw new FileLoadingException('Could not load file foobar.json');}$foobar = json_decode($content);if (json_last_error() !== JSON_ERROR_NONE) { throw new FileLoadingException('foobar.json does not contain valid JSON: '.json_last_error_msg());}
The Safe PHP solution for this is as follows:
Safe-PHP redeclares all core PHP functions. The new PHP functions are acting exactly as the old ones, except they are throwing exceptions properly when an error is encountered. The “safe” functions have the same name as the core PHP functions, except they are in the Safe namespace.
Here’s what the function would look like using this package:
use function Safe\file_get_contents;use function Safe\json_decode; // This code is both safe and simple!$content = file_get_contents('foobar.json');$foobar = json_decode($content);
You can learn more about this repo and access the source code on GitHub. This package also has some automatic refactoring capabilities.
Note: The Safe PHP package is declared as experimenting, and has not reached 1.0 with some outstanding issues remaining.