#native_company# #native_desc#
#native_cta#

Enforcing Coding Standards with PHP_CodeSniffer

By W. Jason Gilmore
on October 21, 2010

Although defined according to formal grammar and syntax, programming languages — like their spoken counterparts — often leave their users with a great deal of leeway for creative expression. For instance, the PHP language does not enforce syntactical rules such as whether a variable or function name must be capitalized, nor does it demand exacting placement of curly braces around statement blocks. This lack of enforcement means that the following two examples are identical in the PHP parser’s eyes:

function salesTax($price, $tax) {
  return $price + $price * $tax;
}

function SalesTax($Price, $Tax)
{
  RETURN $Price + $Price * $Tax;
}

Yet taking such creative liberties with your code can ultimately prove a hindrance to anyone who reviews or even at some later point maintains your code. It can even be singularly counterproductive if you do not maintain stylistic consistency across projects, as you’ll need to continuously re-acclimate to differing syntactical variations.
To help combat this problem within the PHP community, the PEAR team long ago devised a set of coding standards (known as the PEAR Coding Standards), which PEAR package developers must follow. Over the years, the specifications set out in the PEAR Coding Standards have been widely adopted across the entire PHP community thanks to its no-nonsense set of guidelines for indentation, variables, class definitions, comments, and control structures.
I’ve used the PEAR Coding Standards for years and have come to appreciate not only the consistency that their application brings to my code, but also the ability to point colleagues to a community-driven set of guidelines for team-driven projects. Incidentally, applying the PEAR Coding Standard to the above SalesTax() function would result in a definition like this:

function salesTax($price, $tax)
{
    return $price + $price * $tax;
}

However, in light of PHP’s considerable expressive flexibility, how can you actively enforce a coding standard and prevent both yourself and your team members from reverting to bad habits? One great solution called PHP_CodeSniffer is (coincidentally) found in a PEAR package. PHP_CodeSniffer can not only parse PHP code to ensure it meets a particular coding standard but it can also examine your JavaScript and CSS files for potential standards violations.

Introducing PHP_CodeSniffer

Because PHP_CodeSniffer is a PEAR package, you can install it using the PEAR package manager if PEAR is installed on your local system (it probably is):

%>pear install PHP_CodeSniffer

When PHP_CodeSniffer is installed, you will have a command-line interface named phpcs at your disposal. You can peruse its help file by passing it the --help option:

%>phpcs --help