Join David Powers for an in-depth discussion in this video Using parameter and return type declarations together, part of PHP: Strict Data Types.
- [Voiceover] As you've just seen,…different rules apply to scalar type declarations…for parameters and return types…with regard to how weak and strict mode are invoked.…With parameters, it's where the function…is called that matters.…With return type declarations,…it's where the function is defined.…So if you want to use strict typing for scalar values,…both the definition file and the calling file…must be in strict mode,…but that's not necessarily the optimal solution.…I've opened strict_definitions.php…in the chapter three 03_04 folder…of the exercise files.…
It declares the required scalar types…for both parameters and return types.…And because the file begins with the…strict mode declaration,…return types will be enforced.…The first function accepts two integers…and declares the return type as an integer.…The second function, getDiscount,…declares the first argument as a float,…the second one as a boolean, and it says…that the return type should be a float.…The third function accepts a string as an argument…
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