Join David Powers for an in-depth discussion in this video Return type declarations in PHP 7, part of PHP: Strict Data Types.
- [Voiceover] In PHP 7, you can specify…the data type returned by a Function or Class Method.…This is useful, not only as a reminder…of what type of data will be returned,…but also for checking for errors in your Coding Logic.…I've got opened Return underscore Type dot PHP,…which you can find at the Chapter Two.…Zero Two underscore Zero Two Folder of the Exercise Files.…It contains a simple function called Roll Dice,…that uses the PHP 7 Random Int Function…to return an Array of random numbers…between one and six.…
The syntax for Return Type Declarations is simple.…You insert at colon between the closing…parenthesis of the function signature…and the opening curly brace of the function body…followed by the data type.…This function is going to return on Array,…so after the Function Signature,…insert a colon, and then the data type Array.…Now I've added white space on either side of the colon…purely for readability purposes.…The white space is optional.…So if I save that and then run this in the browser,…it returns an Array of five random numbers.…
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