Proposal: best practices for writing PHP

Posted on October 3, 2010

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) {
  • bodies of functions
    function myFunction() {
  • arguments of functions/conditions/loops if written on many lines
    "some other argument that takes place, that's why we put them on many lines",

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:

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


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';

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:


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 = 'foo[at]';

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.


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.