Here are some PHP mistakes I’ve encountered, which have often been very difficult to track down…
Semicolon after while
Recently in some code I was writing, I had a while loop, which looked something like this:
$i = 0; while($i < 20); { //some code here $i++; } |
See that semicolon there? This will cause PHP to silently fall into an infinite loop. You will not get any errors even with E_ALL|E_STRICT error levels – beware of this mistake!
empty() and magic __get method
If you have a class with a __get method, beware of using it with empty():
class Example { public function __get($name) { return 'this should not show up as empty'; } } $e = new Example(); if(empty($e->something)) echo 'This message will show'; $var = $e->something; if(empty($var)) echo 'This message will not show'; |
The first if will evaluate to true, even though the following if with exactly the same string will not!
Missing semicolon after break or continue
This one can be tricky to track down:
for($i = 0; $i < 10; $i++) { for($j = 0; $j < 10; $j++) { if($i == 0) break print $j; } } |
The missing semicolon after the break in the inner loop will cause the code to only output “0” and then exit. This can be tricky to track down, but there is a good way to avoid this completely: always use braces with control structures
In closing
These three are probably the trickiest I’ve actually seen in code, and for #1 and #2 I must admit I was the person who had written the bad code… in my defense, I must say that #1 should be a parse error from PHP (the braces after the while with no “parent”) and #2 does not make any sense! =)
Do you know any more easy to miss errors in code that can be annoying to find?
ps: welcome dzone users
This post has been getting some nice traffic from dzone. I’d like to welcome any new readers – be sure to subscribe to my RSS feed, as you may find my other posts interesting as well. Some examples of my other recently popular posts are what would make template engines actually useful? and the post on how to implement the Data Access Object pattern in PHP
Also, voting for me on dzone is appreciated – just hit the dz button in the Share this list. Thanks!
Be sure to read the comments below for some more mistakes!