5 PHP Mistakes

1. Single quotes, double quotes

It’s easy to just use double quotes when concatenating strings because it parses everything neatly without having to deal with escaping characters and using dot values. However, using single quotes has considerable performance gains, as it requires less processing.
Consider this string:
  1. $howdy = 'everyone';  
  2. $foo = 'hello $howdy';  
  3. $bar = "hello $howdy";  
$foo outputs to “hello $howdy” and $bar gives us “hello everyone”. That’s one less step that PHP has to process. It’s a small change that can make significant gains in the performance of the code.

2. Semicolon after a While

It’s funny how one little character can create havoc in a program, without even being reported to the PHP error logs! Such as it is with semicolons and While statements.
Codeutopia has an excellent example of this little error, showing that these nasty errors don’t even get reported (even to E_ALL!), as it quietly falls into a silent loop.
  1. $i = 0;  
  2. while($i < 20); {  
  3.   //some code here  
  4.   $i++;  
  5. }  
Omit the ; after the while statement, and your code is in the clear.

3. NOT Using database caching

If you're using a database in your PHP application, it is strongly advised that you at least use some sort of database caching. Memcached has emerged as the most poplar caching system, with mammoth sites like Facebook endorsing the software.
Memcached is free and can provide very significant gains to your software. If your PHP is going into production, it's strongly advised to use the caching system.

4. Missing Semicolon After a Break or a Continue

Like #2, a misused semicolon can create serious problems while silently slipping off into the shadows, making it quite difficult to track the error down.
If you're using a semicolon after a "break" or "continue" in your code, it will convince the code to output a "0" and exit. This could cause some serious head scratching. You can avoid this by using braces with PHP control structures (via CodeUtopia).

5. Not Using E_ALL Reporting

Error reporting is a very handy feature in PHP, and if you're not already using it, you should really turn it on. Error reporting takes much of the guesswork out of debugging code, and speeds up your overall development time.
While many PHP programmers may use error reporting, many aren't utilizing the full extent of error reporting. E_ALL is a very strict type of error reporting, and using it ensures that even the smallest error is reported. (That's a good thing if you're wanting to write great code.)

No comments:

Post a Comment

Please Provide your feedback here