PHP is quite flexible in the way you write code. You can write same code in about 10 different styles and it’s still going to work. The problem is when you try to read and understand someone else script. It’s either well documented or completely unreadable.

In my opinion, writing large blocks of documentation is, most of the time, useless and time consuming. It is possible write code in a way that it can be read by anyone with very short amount of documentation. It all starts with naming your functions correctly, dividing long blocks of code in short functions that are self-explained.

So I decided to share some best practices I’ve read or learned over time.

Naming

// INCORRECT
function Getlastmessages()
function GetLastMessages()
function getLastMessages()

// CORRECT
function get_last_messages()

Sure the CamelCase version isn’t bad, but the best way to name methods is by separating words with an underscore.

You should name your classes the same way but by using an uppercase letter as the first letter. (ex: Get_last_message)

Constants also follow the same rule but all letters are in uppercase (ex: GET_LAST_MESSAGE)

HTML Output

Unless the HTML to output is relatively short, you should always close PHP, write your HTML and then open PHP back.

Use the short <?= tag (if enabled on your server) to open PHP to output a variable.

TRUE, FALSE and NULL

// INCORRECT
$var = true;
$var = True;
if($var == null) {}

// CORRECT
$var = TRUE;
$var = FALSE;
if($var == NULL) {}

Always write conditional values in uppercase.

PHP Files ending

As strange as it sounds, you shouldn’t close PHP at the end of PHP file. You should instead include a standard comment at the end and that’s it.

<?php
// PHP CODE HERE

/* End of file index.php
/* Location: ./application/index.php */

Why? Because PHP will close automatically as it reaches the end of the file but more importantly, it will prevent any whitespace or line breaks issues at the end of the file.

UTF-8 File Encoding and Unix line-breaks

Your code editor should always be configured to use UTF-8 encoding and Unix style line breaks. This will ensure compatibility with most languages and servers configuration.