Join David Powers for an in-depth discussion in this video Specifying data types for parameters, part of Strict Data Types in PHP.
- View Offline
- [Voiceover] In this chapter,…we'll take a look at type declarations…or type hints as they were called in PP 5…for objects, arrays, and callback functions.…They work in a very intuitive way.…This is parameters.php which you can find…in the chapter two, 02_01 folder…of the exercise files.…It contains the definition…of a function called convertDate.…It's a rather contrived example, but it's been designed…to demonstrate how to use type declarations…for function parameters.…The function takes three arguments,…date, which must be a DateTime object,…months, which needs to be an array,…and func, which must be a function.…
Without type declarations,…it's important to run a series of checks…on the values passed in as arguments.…So lines three to five have a conditional statement…that check whether date is an instance…of the built-in PP class DateTime.…And on lines six to eight,…we check whether months is an array…and that it contains exactly 12 elements.…And then finally on lines nine to 11,…we pass func to the function_exists function…
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