General – Type safe coding – 1

The issue: In general PHP is loosely typed.
<?php
$foo = "1";
$bar = $foo + 1;
var_dump($foo, $bar);
?>
Output
string(1) “1” int(2)
The normal comparison operators are loosely typed, too.
<?php
$int = 1;
$string = "1";
$bool = true;
var_dump($int == $string);
var_dump($string == $bool);
var_dump($int == $bool);
?>
Output
bool(true) bool(true) bool(true)
This can cause WTF situations
<?php
var_dump( '1' == '1.' );
?>
Output
bool(true)
This may lead to very common mistakes:
<?php
function foo($answer) {
if ($answer > 10) {
return true;
} else {
return $answer;
}
}
if (foo(11)) {
echo "11 is greater 10<br />";
}
if (foo(9)) {
echo "9 is greater than 10<br />";
}
?>
Output

11 is greater 10
9 is greater than 10

Referenced By http://talks.php.net/show/php-best-practices/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s