Join David Powers for an in-depth discussion in this video Changes to error handling in PHP 7, part of PHP: Strict Data Types.
- [Voiceover] The increased support for strict typing…in PHP 7 has necessitated improved error handling.…This is type_error.php…in the chapter two 02_04 folder of the exercise files.…It contains the example of parameter type declarations…from the beginning of this chapter.…The only difference is that down here…on lines 19 to 23, the code that calls the function…is wrapped in a try-catch block.…So let's see what happens…if I run this in PHP 5.…
And I still get a Catchable Fatal Error,…even though I'm using a catch block.…The problem is that the catch block…is looking for an Exception,…and a Catchable Fatal Error is not an Exception.…In PHP 5, the only way to catch…a Catchable Fatal Error is to define…your own error handler.…So let's go back to my editing program…and switch to this file, error_handler.php,…which you can also find in the exercise files…for this video.…This defines a custom error handler…that throws an exception…if the error number is the same as a recoverable error,…and then on line nine,…the custom error handler is asked to set_error_handler.…
First, he introduces the basics of type juggling and type casting in PHP. Then, he reviews strict typing with objects, arrays, and callback functions, which were introduced in PHP 5. He also reviews scalar type hints in PHP 7, which can have unexpected side effects for unwary developers. David concludes with a frank assessment of the practicalities of strict typing, and a simple recommendation that will help most developers use the new feature: define in strict and execute in weak.
- Implicit and explicit type casting
- Using strict data types
- Declaring return types in PHP 7
- Creating scalar parameter declarations and scalar return type declarations
- Assessing the merits of strict data types