Modern PHP coding style guide

The PSR-1 and PSR-2 coding standards define the appearance of the code.

PSR-1 is the basic coding standard for PHP. PSR-2 is a coding style guide.

Before defining them, you need to copy a coding standard from a popular framework, but now PHP has an official coding standard, and all of us should abide by that standard.

简而言之,PSR-1

  • The file should declare symbols (classes, functions, constants, etc.) or cause side effects (for example, generating output, changing .ini settings, etc.), but not both
  • Namespaces and classes must follow the "autoload" PSR: [PSR-0, PSR-4]
  • The class name must be declared in StudlyCaps
  • The method name must be declared in camelCase

简而言之,PSR-2

  • Code must use 4 spaces to indent, not tabs
  • The line length must not have a hard limit; the soft limit must be 120 characters; each line must not exceed 80 characters.
  • There must be a blank line after the namespace declaration, and there must be a blank line after the use declaration block.
  • Visibility must be declared on all properties and methods; summary and final result must be declared before visibility; static must be declared after visibility.
  • The opening bracket of the control structure must have no space after it, and the closing bracket of the control structure must have no space before it.

Executive standard

Knowing and understanding coding standards is essential. Letting your IDE or editor execute it automatically is a big step towards complying with it.

On PHPStorm

It is built-in. Go to "Preferences" -> "Editor" -> "Code Style" -> "PHP", right-click "Set from...", and select "Predefined Styles" -> "PSR1/PSR2"

Sublime text

usesublime-phpfmt