Thread: Type casting
View Single Post
Old 05-25-2008, 11:55 AM   #5 (permalink)
xenon
The Frequenter
Newcomer 
 
xenon's Avatar
 
Join Date: Dec 2007
Location: Bucharest, Romania
Posts: 438
Thanks: 3
xenon is on a distinguished road
Default

Type casting is not made so you can 'transform' strings into integers, arrays, objects, and so on. It's made so you can ENFORCE a certain data type. Its only use is that you can make sure you're getting a certain data type, so you can perform a certain operation. See the example:

PHP Code:
function sum_ints($a$b)
{
    
$a = (int) $a;
    
$b = (int) $b;

    return 
$a+$b;

It's obvious that the sum function can't be used on strings, so that's why we use type casting, so we can enforce the parameters to be integers. If non-integer values are passed in, the function will simply return 0 instead of crashing if you pass in objects as parameters, therefore not breaking application flow. Operator overloading would come useful in here, but that's another problem.
__________________
I have optimistic thoughts, even though sometimes (if not always) life's a bitch.
xenon is offline  
Reply With Quote
The Following User Says Thank You to xenon For This Useful Post:
Orc (05-25-2008)