Proposal: best practices for writing PHP

Posted on October 3, 2010
by

My motivation in writing this proposal comes from years of PHP practice, when I had to use other people’s code and their code looks like garbage so much that I wanted to throw it to the their face rather than using it. I can’t expect everybody to write clear code, but if I could turn the actual world in a world of beauty and smartness, I’d like people to follow the guidelines in this paper. Note that I didn’t pretend to write complete PHP good practices, as I’m just covering the writing aspect of PHP coding, with concerns such as readability and logic in the flow of code.

Good practices for PHP writing

1 – Indent your code

Indentation is very important as it makes your code easily readable. If you use an IDE like Eclipse, you can auto-format your code (although I prefer to format my code by myself) with the ctrl+shift+F key combination (command+shift+F for macs). For a full list of what must be indented, I can see:

  • bodies of conditions and loops (if, elseif, else, while, for, foreach)
    if ($condition) {
    doSomething();
    }
  • bodies of functions
    function myFunction() {
    doSomething();
    andSomethingElse();
    finallyDoOneLastThing();
    }
  • arguments of functions/conditions/loops if written on many lines
    doSomethingComplex(
    $arg1,
    $arg2,
    "some other argument that takes place, that's why we put them on many lines",
    true
    );

2 – Indent your code using tabs

There are basically two ways of indenting code: with (usually 4) spaces, or 1 tab char. People can give arguments for both. I personally use tabs because:

  • in your IDE you can define the width for indentation tabs
  • you press the key just once
  • you don’t risk to mistake, forget or add an extra space
  • spaces are already used to separate operators
  • it seems more logical to have just ONE element, since you’re moving your code for just ONE level

3 – And don’t forget to indent SQL queries as well

It’s something I’ve seen with some developers: they used not to indent SQL queries in their code. Ok, with short queries it’s no big deal, but for big queries it can become a real mess. This is, for example, the kind of indentation I use for my SQL queries:

'SELECT
id,
username,
email,
visible,
activated,
date_last_login,
password,
password_salt
FROM
`accounts`
WHERE
username = "' . mysql_real_escape($username) . '"'

4 – Be consistent in your naming conventions

Naming conventions are very important. I can’t say that a convention is better than another, as it really depends on the developer itself, or the framework he uses. However, whatever is the convention you choose to use, please be consistent! Don’t name some variables camel-case, and some other with underscores. Choose one and stick to it.

Anyway, I give you my personal naming conventions (which more or less come from good practices for Java):

  • class names are camel-case and start with an uppercase letter. Example: MyClass
  • method names are camel-case, but start with a lowercase letter. Example: doSomething()
  • attributes are camel-case, and start with a lowercase letter. Private/protected attributes have an underscore prefix. Example: publicAttribute, _privateAttribute
  • constants are all uppercase, and words are separated by underscores. Example: APPLICATION_ROOT_PATH

Example:

class MyClass {
private $_firstAttribute;
private $_secondAttribute;
 
public $onePublicAttribute;
 
public const ONE_CONSTANT = 4;
 
public function __construct($firstAttribute) {
$this->_firstAttribute = $firstAttribute;
}
 
public function doSomething() { }
 
public function doSomethingElse() { }
}

5 – Use meaningful names

The choice of your vocabulary when you write code matters, for example, it’s good to well describe the behaviour of your methods. Use meaningful method names like:

public function getPosts(); // return all posts
public function getPostById($id); // return a post according to its ID
public function writePost($post);  // write the HTML code for a post

Usually, it works well to use a verb for method names, since methods can be considered as actions executed on your object. Below is an example of meaningless names (from the WordPress API, read things that suck in WordPress):

function the_title(); // what the title? return the title, write the title, fuck the title?
function get_search_form(); // write HTML code, but doesn't return anything. WTF?

See the difference? Hopefully WordPress provides documentation to make it up, but with good names you can avoid your reader (or the future you) some troubles and loss of time.

6 – Write in english

Maybe english is not your mother tongue. However it’s the global language for business and, guess what, yes computing! If you think that your work is not worth going beyond the borders of your country, then go ahead and write code in french or german! I do think sharing is a global thing, that’s my idea of sharing, that’s why I never write a word of french in my code.

7 – Don’t use one-letter variables

Maybe the only acceptable one-letter variables are iterators ($i, $j, $k…) as it’s common in maths to use them (and convenient for coders), but for everything else, a meaningful name (preferably without abbreviation) is better.

8 – Don’t use leet

Geeks think it’s funny to write leet (so do I). But let’s be serious when coding, let’s avoid leet for variable names. Bad example (from true story):

$een = 1; // in
$oot = someFunction($een); // out

9 – Comment your code

We never say it enough: commenting your code is IMPORTANT. Even yourself are likely not to understand your code again some weeks after you write it, so how can other developers? Since I often get mad about this, my mates often ask me “ok you want me to comment until the last $i++ to say I increment a variable, is that what you want?!“. It’s hard to make a rule on what must be commented and what’s not needed. The best is that for every block of code, you ask yourself “If I had to read this in 3 months, will I get what I meant to do there?“, if the answer is no, comment it!

10 – Don’t invent words

Still in the same range of ideas, I’ve always found class names with invented words were stupid and not helpful. Example: I used to work on another developer’s code, and he called one of his classes “Xparser”. When I asked him why the letter X, he said there was no special reason, just it sounded cool. Damn it, I was thinking about an XML or XHTML parser or whatever related, but it was something totally different. Don’t mislead your readers with invented words, when real words can do the trick.

11 – Don’t copy extra variables

If you’re to use a variable only once, no need to set the variable (well, it depends on the context of course, use your logic). Example:

$q = 'SELECT * FROM table';
mysql_query($q);

Could be easily contracted in (and it’s not less readable):

mysql_query('SELECT * FROM table');

It’s still a line of code less to read.

12 – Always declare and initialise your variables

Although PHP does NOT require you to declare and initialise your variables before you use them, it can be good to do it. First of all, for performance issues. Secondly, to well prepare your reader to what he’s going to see below. Thirdly, for yourself to have a pretty overview of your application/script while coding it: it’s like a palette of variables that you know you’re going to use to paint your script.

13 – Put spaces between your operators

Maybe it’s just me, but I read code more easily when words and operators are spaced. I used to know a guy who never put spaces between operators. He said he was used to it, and I don’t doubt he can read himself, but can the others? For example, something like that:

if($nbPosts>0&&$userAuthorized===true){
$myVariable=myFunction('foo','bar',$foo.'-'.$bar);
}

could end up in something like this:

if ($nbPosts > 0 && $userAuthorized === true) {
$myVariable = myFunction('foo', 'bar', $foo . '-' . $bar);
}

Which one do you prefer to read? Think about your readers and yourself!

14 – Align equal signs when declaring many variables

It can be good to align the equal signs of variable declarations when you declare several variables in a row. It improves readability for your reader (and possibly, again, yourself).

// declare some variables
$username = 'Cyril';
$userId = 1;
$password = 'ahahah';
$email = 'cyril.mazur[at]gmail.com';

This works better when you indent your code with tabs, because it automatically aligns your cursor on a grid and you don’t have to count spaces to have the right alignment.

Conclusion

This is pretty much everything that came to my mind about what I think are good practices for writing PHP code. Some points can be controversial, so if you disagree on some point or want to add something, please feel free to use the comment box below. I hope this helps, and I’m really thinking about coming up with a more complete set of guidelines (or other sort of material that I have in mind :-) will tell you about it sooner or later)

About the author

Cyril Mazur is a serial web entrepreneur with experience in various fields: online dating, forex & finance, blogging, online advertising... who enjoys building things that people like to use.

7 comments

  1. retnip
    on October 4, 2010
    Hard tabs are frowned upon....as they are NOT portable. If you are using an IDE as you suggest, then use soft tabs.
  2. Cyril
    on October 9, 2010
    You're very right retnip. Although hard tabs have my personal preference, it's old fashioned now and not portable.

    I always admit my own errors when I'm wrong ;-) I'll correct my post as soon as I've got more time. (and gotta correct my own habits too...)

    Have a good weekend!
  3. Julius Pablo Ballesteros
    on February 9, 2011
    Hi, i am Julius Pablo Ballesteros, an IT Student From University of the Cordilleras in the Philippines, i am still a novice, in writing PHP codes, the guidelines in this paper are good practices for writing PHP code, specially for students like me who are still learning and practicing to write PHP codes.and as i go over your proposal, i agree that these practices will help me/us to become professional programmers in the future.
  4. Cyril
    on February 9, 2011
    Thanks for your comment Julius, am glad it helps.
  5. Geline Lutong
    on February 11, 2011
    Good day! I'm a student from the University of the Cordilleras, Philippines. Reading your proposal made me realized things I should be implementing in my codes. These things include commenting a code or a block of codes, indenting SQL queries, declaring variables and aligning equal signs. These guidelines will be really useful for me to become a professional web developer. Thank you for the tips.

    In addition, for long codes (like 500 plus lines), I think it will be good to put a block of comments before the script which indicates the lines of codes and what these codes are. This way, the developer and specially the readers will easily find the codes they wanted to look into. I hope it will be helpful.
    Example:
    /*
    Lines 20-80 codes for …
    Lines 81-110 codes for …

    */
    //starting codes here
  6. Jeremy Perez
    on February 14, 2011
    Hi i am Jeremy Perez of the University of the Cordilleras

    PHP is a nice language for some tasks. Lots of good software uses it. No other language makes it so convenient to mix code and html, which is great for lone web developers who are also programmers. I've found it pretty useful for running my page, mainly because I can so easily put code in the middle of my content, and keep the overall per-page authoring overhead down...

    This is a very good programming language for all the web developers and it can help also a student like me to make our projects more easily special in web programming subjects....

    but i have a question...
    what are the major problems in using a php programming language..:)

    t
  7. Alyssa R. Cruz
    on October 17, 2011
    Good day Mr. Cyril Mazur! My name is Alyssa Cruz, an IT student from the University of the Cordilleras, Philippines. I find this article/site you made a big help especially for beginners like me.

    As a student having Web Development Track as my Major, it is really my passion to make websites and create unique designs of my own but I know that I have a lot of areas to improve.

    PHP really caught my attention and I'm really interested and willing to learn. Your site gave me ideas on what and which steps should I do to be, of course, a good web developer.

    It's nice that you have posted some of the guidelines that we can follow and consider as a stepping stone steps in creating our own sites.

    I'll be waiting for what you have said about coming up with a more complete set of guidelines using your knowledge!:)

    Merci et bonne journée à venir!:)

Leave a Reply