Join David Powers for an in-depth discussion in this video Scalar return type declarations, part of Strict Data Types in PHP.
- [Voiceover] In one respect, scalar return type…declarations do what you would expect.…In weak mode, they use type juggling…to return the specified data type.…In strict mode, they raise an error…if the wrong type is returned.…But there's an important difference…in how strict mode is interpreted.…I've opened scalar_returns.php…in the ch3>03_03 folder…of the exercise files.…To make it easier to focus on the behavior…of return type declarations,…the examples don't declare the required data types…for the parameters.…
The first function multiplies two values…and declares the return type as int,…in other words, an integer.…The second function divides two values…and declares the return type as float.…A third function returns a string…but declares that the return type should a bool,…a boolean true or false.…And the fourth function just returns…whatever value is passed to it…but declares that the return type should be a string.…And on lines 18 to 24, each function is tested,…and the result is inspected using var_dump…to show both the data type and the value.…
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