Automatic type conversion

As PHP is loosely typed, it will automatically convert one type to another whenever possible. Problems with automatic conversion occur when either no meaningful conversion is possible, or when conversion yields unexpected results. For example, calling "print" on an array makes PHP print out "Array"; it doesn't automatically convert the array to a string of all its elements. Treating an object like a string has its own unique behaviour, but that's not too important right now.

The unexpected results occur when PHP converts values and produces unhelpful results. This is not PHP being badly written, more that your code needs to be more explicit. For example, converting from a boolean to a string will produce a 1 if the boolean is set to true, or an empty string if false. Consider this script:

<?php
    $bool
= true;
    print
"Bool is set to $bool\n";
    
$bool = false;
    print
"Bool is set to $bool\n";
?>

That will output the following:

Bool is set to 1
Bool is set to

As you can see, it hasn't printed out a 0 for false. Instead, nothing is printed, which makes the output look incorrect. To solve this problem, and others like it, tell PHP how you want the value converted by typecasting. The above script should be rewritten to typecast the boolean to an integer, as this will force boolean true to be 1 and boolean false to be 0.

<?php
    $bool
= true;
    print
"Bool is set to $bool\n";
    
$bool = false;
    print
"Bool is set to ";
    print (int)
$bool;
?>

This time the script outputs 1 and 0 as we wanted.

 

Next chapter: Forcing a type with type casting >>

Previous chapter: Checking a variable is set

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar