Join David Powers for an in-depth discussion in this video Explicit type casting, part of Strict Data Types in PHP.
- View Offline
- [Voiceover] Occasionally it becomes necessary…to coerce a value to a specific data type…using type casting to get the code to do what you want.…There's an example of this type of situation…in the chapter 01, 01_03 folder…of the exercise files.…This is books.xml which contains the names…of authors and the titles of novels they've written.…To display the authors and titles,…the XML is loaded into this other file,…casting.php, as simple XML.…
Then on line five, a variable is initialized…as an empty string to store the previous author's name.…And this foreach loop on lines nine…through to 18 iterates over the simple XML…to create a definition list.…I want to display the author's name only once,…so the loop begins with a conditional statement…that compares the current author's name…with the value stored in $previous.…The first time the loop runs,…$previous is empty…so the author's name should be displayed.…
Then we display the title.…And at the end of the loop,…we store the current author's name as $previous.…So the next time the loop runs,…
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