Join David Powers for an in-depth discussion in this video Return type declarations with an interface, part of Strict Data Types in PHP.
- [Voiceover] You need to be careful…when using return type declarations…for a class that implements an interface.…To illustrate this to you,…I've opened LondonWS.php in the chapter two,…02_03 folder of the Exercise Files.…It defines a custom class called LondonWS…that implements an interface called RegularEvents.…That interface is defined here, in RegularEvents.php,…which you can also find…in the Exercise Files for this video.…The interface requires an implementing class…to define two public methods:…getNext and getNextYearDates.…
At the moment, neither the interface…nor the class definition uses return type declarations.…So let's return to LondonWS.php…and add some return type declarations.…London Web Standards holds its regular meetings…on the third Monday of each month.…So, the getNext method…creates a PHP DateTime object,…and then it uses that to find the third Monday of this month…or, if the third Monday has already passed,…the third Monday of next month.…
So it's going to return a DateTime object.…So, the return type, we can declare it up here,…
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