Join David Powers for an in-depth discussion in this video Implicit type casting, part of PHP: Strict Data Types.
- Implicit type casting, or type juggling as it's called…in PHP, generally works in a very intuitive way.…But if you're new to PHP, the way some strings…are handled in calculations might come as a surprise.…I've opened "juggle.php"…in the "ch01\01_02 folder"…of the exercise files.…Line two initializes a variable, "myVar,"…and assigns it the value 42.…Then myVar is passed to var_dump…to inspect the data type and value.…
And if I run this script, we can see…that the data type is "int," in other words, an integer,…and the value is 42.…Even though myVar has been initialized as an integer,…PHP will let me assign not only a different value,…but also a different data type to this variable.…So if we add a new line on line three,…add myVar, and make it a boolean "true,"…save that, and run the script again,…PHP takes the change in its stride.…
There's no error.…MyVar is now a boolean with the value "true."…And we can change it again.…MyVar, we'll make it a string,…and the value of the string will be "false."…Save that, run the script again.…
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