DEV Community

Dollar Dev
Dollar Dev

Posted on

Top 10 PHP coding standards

PHP coding standards are a set of guidelines and best practices that developers follow to ensure consistency, readability, and maintainability of code. Adhering to coding standards is essential for collaborative development, as it promotes a uniform coding style across a project or organization. Here are common PHP coding standards:

1.PSR Standards
Many PHP projects and frameworks follow the standards defined by the PHP-FIG (PHP Framework Interop Group). Notable PSRs include PSR-1, PSR-2, PSR-4, and PSR-12.

2.Indentation
Use spaces for indentation instead of tabs. PSR-2 recommends using four spaces for each level of indentation.

3.Line Length
Limit lines to a maximum length, commonly 80 or 120 characters per line. This enhances code readability, especially in side-by-side comparisons.

4.Opening and Closing PHP Tags
Use <?php for opening PHP tags, and avoid using the short tags (<?). For files that contain only PHP code, omit the closing tag ?> to prevent unintended whitespace.

5.Namespace and Class Naming
Use a namespace, and follow an autoloader-friendly directory structure. Class names should be declared in StudlyCaps (PascalCase).

namespace Vendor\Package;

class ClassName
{
    // Class implementation
}
Enter fullscreen mode Exit fullscreen mode

6.Class Constants, Properties, and Methods
Constants should be declared in uppercase with underscores as separators. Properties and methods should use camelCase.

const MAX_ATTEMPTS = 3;

class MyClass
{
    private $myProperty;

    public function myMethod()
    {
        // Method implementation
    }
}
Enter fullscreen mode Exit fullscreen mode

7.Control Structures
Place control structure keywords (if, else, for, while, etc.) on a new line with an indentation. Use braces even for single-line statements.

if ($condition) {
    // Code block
} else {
    // Code block
}
Enter fullscreen mode Exit fullscreen mode

8.Function and Method Calls
Do not use spaces between the function or method name and the opening parenthesis. Add a space after commas in argument lists.

myFunction($arg1, $arg2);

$object->myMethod($arg1, $arg2);
Enter fullscreen mode Exit fullscreen mode

9.Array Declaration
Use the array() syntax for array declaration rather than the short [] syntax. Add a space after the comma.

$myArray = array('apple', 'banana', 'orange');
Enter fullscreen mode Exit fullscreen mode

10.Doc Comments
Use doc comments to document classes, methods, and properties. Follow the PHPDoc format for consistency and clarity.

/**
 * Short description.
 *
 * @param  string $param1 Description of param1
 * @param  int    $param2 Description of param2
 * @return bool   Description of the return value
 */
public function myMethod($param1, $param2)
{
    // Method implementation
}
Enter fullscreen mode Exit fullscreen mode

And one more additional recommendation:
Integrate tools like PHP_CodeSniffer and follow the predefined coding standards (e.g., PSR-2) by creating configuration files. Automate the process of code checking within your development workflow.

# Example usage of PHP_CodeSniffer
phpcs --standard=PSR2 path/to/your/code
Enter fullscreen mode Exit fullscreen mode

These coding standards help create a unified coding style across PHP projects and facilitate collaboration among developers. It's essential to choose and consistently follow a set of coding standards that align with the project's requirements and the wider PHP community.

Top comments (5)

Collapse
 
sroehrl profile image
neoan

PHP has been evolving quite rapidly over the past few years. That's why PSR-2 has been declared deprecated since 2019 in favor of PSR-12. While code style is an important tool for clarity and cooperation, the keywords "MUST", "SHALL", etc. give a little insight into how difficult it is to set out standards. Let's look at one of your examples:

/**
 * Short description.
 *
 * @param  string $param1 Description of param1
 * @param  int    $param2 Description of param2
 * @return bool   Description of the return value
 */
public function myMethod($param1, $param2)
{
    // Method implementation
}
Enter fullscreen mode Exit fullscreen mode

If we use typing and a declaratively name variables, what is the remaining advantage of the doc block, other than adhering to a convention?

public function isCurrentUser(string $userName, int $userId) : bool
{
  // ...
}
Enter fullscreen mode Exit fullscreen mode

So yes, code style should be taken seriously, but spending time with variable naming and coding principles (SOLID) will make your life exorbitantly easier. Especially since modern IDEs take care of adhering to PSR-standards for you (as always, I recommend PHPStorm)

Collapse
 
joolsmcfly profile image
Julien Dephix

php-cs-fixer's no_superfluous_phpdoc_tags rule will remove those comments for you :)

Collapse
 
ta_phpwebdev profile image
Dollar Dev

Yes, this article is more for beginners, to roughly understand what standards there are for development. In a real project everything may be different

Collapse
 
sroehrl profile image
neoan

What was important as beginners for us? I, for example, wondered why coders are such sticklers for code style. I wondered why different teams had different standards, pre-commit hooks, or opinionated ways of doing things a certain way in general.
So reading this article, I frankly wondered what I would do if an entry-level dev tried to convince me of things like "we should use array() instead of []". I would have probably first asked them why they thought this would be an advantage.
See, it's my firm believe that coding is a mind-set. And if somebody can't explain why one should stop at a stop-sign, I either can't use that person for city-planning in the future, or have to explain what the sign tries to solve for.

Like all standards, code style is a necessity for the present, but a hurdle for the future. That's why I felt compelled to open up the discussion on this. Not to disagree with the content of your article, but to raise healthy skepticism to the question "Are these the top 10 PHP coding standards?"

Thread Thread
 
ta_phpwebdev profile image
Dollar Dev

Yes, I made this article as dry as possible, because for me this topic is full of reasoning and I also think that coding is a mindset. Of course, these are not the top 10 unbreakable standards. Rather, these are standards that are worth paying attention to and knowing that they exist.