PHP, as most of us know, has weak typing. For those who don't, PHP.net says:
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.
Love it or hate it, PHP re-casts variables on-the-fly. So, the following code is valid:
$var = "10"; $value = 10 + $var; var_dump($value); // int(20)
PHP also alows you to explicitly cast a variable, like so:
$var = "10"; $value = 10 + $var; $value = (string)$value; var_dump($value); // string(2) "20"
That's all cool... but, for the life of me, I cannot conceive of a practical reason for doing this.
I don't have a problem with strong typing in languages that support it, like Java. That's fine, and I completely understand it. Also, I'm aware of—and fully understand the usefulness of—type hinting in function parameters.
The problem I have with type casting is explained by the above quote. If PHP can swap types at-will, it can do so even after you force cast a type; and it can do so on-the-fly when you need a certain type in an operation. That makes the following valid:
$var = "10"; $value = (int)$var; $value = $value . ' TaDa!'; var_dump($value); // string(8) "10 TaDa!"
So what's the point? Can anyone show me a practical application or example of type casting—one that would fail if type casting were not involved?
I ask this here instead of SO because I figure practicality is too subjective.
Edit in response to Chris' comment
Take this theoretical example of a world where user-defined type casting makes sense in PHP:
- You force cast variable
- You attempt to store a string value in the variable
- PHP throws an exception!! <--- That would make sense. Suddenly the reason for user defined type casting exists!
The fact that PHP will switch things around as needed makes the point of user defined type casting vague. For example, the following two code samples are equivalent:
// example 1 $foo = 0; $foo = (string)$foo; $foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo; // example 2 $foo = 0; $foo = (int)$foo; $foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;
Guess who found himself using typecasting in a practical environment? Yours Truly.
The requirement was to display money values on a website for a restaurant menu. The design of the site required that trailing zeros be trimmed, so that the display looked something like the following:
Menu Item 1 .............. $ 4 Menu Item 2 .............. $ 7.5 Menu Item 3 .............. $ 3
The best way I found to do that wast to cast the variable as a float:
$price = '7.50'; // a string from the database layer. echo 'Menu Item 2 .............. $ ' . (float)$price;
PHP trims the float's trailing zeros, and then recasts the float as a string for concatenation.