Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

TheCodingMachine.io:
Safe PHP - Throwing Exceptions Instead of Returning False
Sep 27, 2018 @ 16:47:44

On TheCodingMachine.io there's a tutorial posted by David NĂ©grier covering an interesting idea when handling "falseness" in your PHP application - throwing exceptions rather than returning false. In this case, he introduces the "safe" library to help make this easier.

At TheCodingMachine, we are huge fans of PHPStan. PHPStan is an open-source static analysis tool for your PHP code. [...] PHPStan has this notion of "levels" and we strive on each of our projects to reach "level 7" (the maximum level). But PHPStan is constantly improving, and reaching level 7 becomes harder and harder as the tool becomes more strict (this is a good thing!).

The post includes an example of this increasing strictness, showing how a more recent check looks at a file_get_contents call and ensures all possible return values are evaluated (it returns false when it errors). They refactor the code example to more correctly check for this, but losing some of the "expressiveness". The tutorial then spends some time talking about the history of PHP and why things return false rather than throw exceptions on error. It covers some of the basics of how the safe library works and a PHPStan extension that can help find places that need to be wrapped by "safe" to throw exceptions when false is returned.

tagged: safephp library exception false return value tutorial package

Link: https://thecodingmachine.io/introducing-safe-php


Trending Topics: