PHP ‘Good’ Practices

This article lists a number of coding practices that should be followed in professional environments. Most of these practices are not of my invention, they have been accumulated from numerous blog and forum posts throughout the Internet written by expert PHP developers. I am just listing them here, along with few of my own conventions as a personal checklist for code review. If you are benefited by any of these, I’ll take that as a bonus 🙂

Disclaimer: I didn’t go with the usual ‘Best Practice’ term as I am personally opposed to it. A certain coding practice should not be called best if everyone follows it. Someone could come up with a better convention, thus invalidating the previous. Hence the title ‘PHP Good Practice'(I think ‘Best Practice so far’ should be a more accurate term, but it doesn’t sound as cool).

1. Use ‘===’ instead of ‘==’ for equality. ‘===’ compares both the types and values of its operands, unlike ‘==’ which only compares values. (That is why 0 == ‘0’ returns true in PHP, but what about 0 == ‘test’ ? Take a look.)

2. Avoid function calls within for() loop control blocks. For example,

for( $i=0; $i<count($x); $i++ )

The count($x) is called at every iteration. Rather call it before the for loop.

3. When dealing with strings, see if you can use the string library functions and avoid the regex. For example, suppose you are looking for a certain word (say ‘XML’) inside a string. You can simply use strpos() instead of preg_match(), since the word you are looking for is unchanging.

4. An improper use of strpos() would be like this:

if(strpos($substring,$string)){ //do something}

strpos() returns the position of the first occurrence of the substring within a string, otherwise returns false. The above condition will fail if you are looking for ‘abc’ inside ‘abcdef’, because PHP treats 0 and false to be equal. The following code better handles this situation

if(strpos($substring,$string) !== FALSE)
{ //do something}

This further proves the point number 1.

5. Use single quotes for wrapping strings. PHP looks for variables inside double quotes making things slower.

6. If a class method can be static, declare it static. Speed improvement is by a factor of 4.

7. var_dump() is better than print_r() for debugging as it prints both type and value of the data. You cannot tell an empty string from NULL using print_r().

8. $row[’id’] is 7 times faster than $row[id].

9. To find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time().

10. Variables should be initialized before being used. Makes the code less sloppy. Also incrementing an initialized variable is faster than incrementing an uninitialized one.

11. I recently found a code where the developer is checking if a certain constant is defined before invoking an action. His code was like This

if(MY_CONSTANT)
{
//do something
}
else
{
//do something else
}

If for some reason MY_CONSTANT is not defined, PHP will still execute the statements in the if block, because MY_CONSTANT will then be a string and if(MY_CONSTANT) will return true. The proper way to do this will then be

if(defined(MY_CONSTANT))
{
//do something
}

12. Close database connection, free resources once you are done with them. It improves execution speed.

13. To improve robustness of the application, make use of try-catch statements. Define distinct exception classes for distinct operations (e.g. DatabaseException, FileNotFoundException) and handle them properly for graceful crash of the code.

14. Avoid the ‘PHP White Screen of Death’ in production environment. Use custom fatal error handlers. Here is a good article about them.

Advertisements

One thought on “PHP ‘Good’ Practices

  1. Great post, and I like your term ‘good practices’. I don’t think I’ve used strpos() in that situation, but I may not have thought about the case when it returns 0. That’s a good catch.

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