Join David Powers for an in-depth discussion in this video Scalar parameter declarations, part of Strict Data Types in PHP.
- [Voiceover] Let's examine how scalar type declarations…for parameters work in both weak mode and strict mode.…This is "scalar_params.php" which you can find…in the "ch03\03_02" folder of the exercises files.…It defines four functions…and then tests each one by displaying the results.…The first function "subtractIntegers" takes two arguments,…both of which are declared as "int"…in other words, an integer.…One is subtracted from the other…and the result is returned.…
The next function does the same except…that both arguments are declared as being "float"…in other words, floating point numbers.…The third function takes a single string as its argument…and returns it embedded in the longer string.…And the fourth function, "getDiscount" takes a "float"…as it's first argument.…The second argument is declared as "bool"…in other words, a Boolean true or false.…Depending on whether on "$isMember" is true or false,…a different discount is applied…and then the result is returned,…formatted to two decimal places.…
Then on lines 19-22, each of these functions is tested,…
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