10 Recommended PHP Coding Tips To Enhance Your Daily Coding Skills


PHP Coding Tips

PHP Coding Tips

Some say code is beauty, some say code is poetry and it is up to you (the developers) who writes such poetry and make it a beauty. Beautiful written code prevents coding hazards, took less time to understand by any other developers.

So, no matter if you are a novice developer or an advanced developer, these coding tips will surely help you in daily coding habits.

  1. Enclose PHP code between HTML markup and not vice-versa

HTML markup should not be enclosed between php code. It clearly breaks the design flow. It also breaks the flow of html tags, when you design a layout with tools like Adobe Dreamweaver. You cannot actually see the opening and closing of the html tags if you put half of your html markup inside the PHP. See the image below:

The Good & Bad Practices of PHP Coding

The Good & Bad Practices of PHP Coding

Note the php tags are enclosed inside the html elements. This way your code / html markup is clearly visible and you can easily read it as well. Your coding tools such as dreamwiever, notepad++ will love it too, because they can easily read as your markup.

  1. Document your script

Start your coding by writing little bit information about the code file (script) itself. Look at the example given below:

/*----------------------------------------------------------------------------
     @description:   [ add script purpose & description ]
     @created on:    [ add date of creation ]
     @author:        [ add author name, shows authorization of code ]
     @usage:         [ for lib/class files; show an small example of usage ]
------------------------------------------------------------------------------*/

It can have any format your needs. This is much often I use for my project coding. You can have more attributes like: @last modified, @parent script, @class file, @warning etc.

The idea is to define some information about the script so that anybody (off course human) who is reading the code can easily get to know what will this script do before going into the code.

  1. Naming a variable

Use proper variable names and function names. When I say “proper” that means it should be “readable” by human being. Avoid any variable names like $i, $a, $b etc.

Use at least 4-5 characters long variable names. Give as much as detailed variable name, if possible.

For example: $counter_a , $counter_b would be better example. Another example of proper variable naming can be:

 $commentHtmlCode = getHtmlCode($authorName, $authorId);

The code above gives us clear information of what’s happening in it. Sometimes, there might need not to write a comment for such coding. The code (var/function names) is clearly telling you what is actually happening in it.

  1. Comment should tell you a story

In more technical words, we often call it “Code Documentation”. Commenting your code is important as much as documenting your script, like I described in point number 2. Consider your comments a story describing the system. Your comments should be enough to describe you what is actually happening in the bunch lines of code. Example:

  /*---------------------------------------------------------------------------
    Checks for the HTTPS based connection and redirect users back to https
    if they access the site with http://
  -----------------------------------------------------------------------------*/
    if($_SERVER['HTTPS']!="on"){
        $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        header("Location:$redirect");
    }

I think I do not need to describe the code above, the comment given itself is telling you the whole story of these 3 lines of code. This kind of commenting is very much useful and strongly recommended when you are dealing with big size project which has thousands lines of code and hundreds number of script files.

  1. Use .php as PHP file extension

There is lots of different extension variants on PHP files (.html, .php, .php3, .php4, .phtml, .inc, .class…). Always use the extension .php. Always use the extension .php for your class and function libraries.

The use of .php makes it possible to enable caching on other files than .php.
The use of .inc or .class can be a security problem. On most servers these extensions aren’t set to be run by a parser. If these are accessed they will be displayed in clear text.

  1. Avoid deep include() traversing

There is a need to break a web page into few blocks, parts where you can put your code in different php files and call all of them in a single parent script.

An example: Lets say you are having one parent script called parent.php and 3 more files header.php, content.php, sidebar.php, footer.php, which are included in the parent.php. So here you are making one call for each of the file in parent.php. It might be possible that header.php is calling other.php file to include functionality from it. Same way it could be possible other.php is calling some other file(s). There is a deep traverse of 3 levels.

  • Level 1: parent.php is calling header.php
  • Level 2: header.php is calling other.php
  • Level 3: other.php is calling more.php file(s)
  • …………
  • Level n: going more deep

Avoid such deep traversing of scripts. Normally, 2 level deep traverse considered as fine.

  1. Add default: in switch{} statement

If you are having a series of if statements in your code, convert this into single switch statement with all the cases, plus it is recommended to have default case to catch errors. A default case matches anything that wasn’t matched by the other cases. For example:

switch ($code) {
    case 'html':
        echo "This is html markup.";
        break;
    case 'js' :
        echo "This is javascript code.";
        break;
    case 'php':
        echo "This is php code.";
        break;
    default:
       echo "This string is simple text.";
}

Notice the default case which is being executed when no other cases was matched.

It id recommended to add default case in the switch statement always.

  1. Enhance readability with proper usage of braces {}

Developers generally follow three types of brace placement strategies. First and second are acceptable whereas third should not be used.

First: clean & clear

 if ($condition)
 {
    ...
 }

Second: UNIX style

 if ($condition){
    ...
 }

Third: garbage collection

 if ($condition){ ... }

I called third as a garbage collection because it only makes your code a complete garbage. This makes tough to read and understand the code.

Even if you have one line under the braces, expand it in different lines. The primarily focus here to enhance the readability of code by human being. Machine, complier can even read it in any form but it is much much important to make the code readable by the person who is writing the code and for other developers.

  1. Use single quotes ‘…’ and avoid double quotes “…”

Double quotes generally used where we need to enclose a variable inside the string. Whenever we add double quotes in code, we actually asking php to look for variable. This doesn’t make any difference in performance but imagine a case where you have thousands lines of code along with such double quoted strings. Your script will take hell lot of time to render and you won’t be able to find out what is the actual issue in the code.

Bad practices

 $myName = "I am Sachin Kumar";

 $sentence = "I am ". $myName . " and I love blogging.";

Good practices

 $myName = 'I am Sachin Kumar';

 $sentence = 'I am '. $myName . ' and I love blogging.';

To run scripts fast in your server, avoid double quotes at all costs. Even if you’re working with variables use dot (.) operator to concatenate the string with variables..

  1. php.net is the ultimate source of knowledge

php.net is the only reliable and ultimate source of php knowledge on internet. Whenever I come across with some issues or needed some help, I always check php.net for the solution. I didn’t need to go further any search for any help while I am on php.net site. Make it as a daily habit of yours to use php.net for any kind of php help.

Conclusion

Please note that programming, concepts, logic remains always same despite of different programming languages. These tips are recommended for PHP though very much applies to others as well, like JavaScript, HTML, Rubby etc.

Please note

This is not a priority list nor in any order. This is a simple generic list gathered from my personal experience (couple of copied from net) to enhance our daily coding habits. Hope you find them useful too.

Resources

For more tips, please follow the links below and If you guys have some tips to share, please post them in comment section below.

About SachinKRaj

Sachin is a web application developer, technology blogger and web addict! He has over 6 years of web development experience and he writes tutorials primarily focused on LAMP, Ajax, Api's, jQuery etc. He is usability expert and he always likes to share his knowledge with people.

, , , , ,

  • Rabby Bhuiyan

    So much helpful post. This is exactly what I was looking for ! :D

    • SachinKRaj

      Thanks Rabby, Glad it helps you. :)

  • windows vps

    Terrific work! This is the kind of information that are supposed to be shared across the internet. Shame on the search engines for not positioning this submit upper! Come on over and visit my website . Thanks =)

    • SachinKRaj

      Thanks :)

      • Rabby Bhuiyan

        Man, i think that comment is a spam :P

        • SachinKRaj

          I know, its a marketing spam. So wat, I found the words so good… :)

  • Asal

    Thanks it is very usefull for beginers like me.. :)