General – Exceptions

The issue: PHP has exceptions now, cool but dangerous.
  • Exceptions are a great tool for handling exceptional states
  • Exceptions are often misused and become regulars
  • Exceptions may make PHP leaking
<?php
function foo() {
if ($user_input !== "Hello!") {
throw new Exception("User input wrong");
}
}
?>
Only use exceptions, when your application ends up in an exceptional state
<?php
function bar() {
if (connection_timedout()) {
throw new Exception("Connection timeout");
}
}
?>
Exceptions leak a little bit of memory when thrown e.g. out of for loops
<?php
foreach ($i = 1000000; $i > 0; $i--) {
throw new Exceptions("Hehe, I'm leaking");
}
?>
Allocated memory from the for-loop-header is not freeed correctly.

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/