3.3 Automatic type conversionThis is NOT the latest copy of this book; click here for the latest version.
As PHP is typeless, 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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|