PSR-1 and PSR-2
PSR: PHP Standards Recommendations
PSR-1: Basic Coding Standard
PSR-2: Coding Style Guide
擁有共同制定的Coding Style可以讓程式碼更佳容易維護。
No Tabs
請用4 Spaces取代tab,如果你是使用vim可以在.vimrc加入:
" expand TABs to spaces set expandtab "et " set TAB's width set tabstop=4 "ts " auto indent width set shiftwidth=4 "sw
Omit ?>
and end with a single blank line
開頭可使用 <?php
或 <?=
結束時不需要 ?>
並留一行空白
SHOULD NOT do both side effects and declarations
Side Effects不要跟Declarations放在一起
Side Effects:
<?php // side effect: change ini settings ini_set('error_reporting', E_ALL); // side effect: loads a file include "file.php"; // side effect: generates output echo "<html>\n";
Declarations: (classes, functions, constants, etc.)
<?php // declaration function foo() { // function body } // conditional declaration is *not* a side effect if (! function_exists('bar')) { function bar() { // function body } }
Leave one blank line after…
在 namespace declaration 和 use namespace 下方留一行空白
<?php namespace Vendor\Package; use FooClass; use BarClass as Bar; use OtherVendor\OtherPackage\BazClass; // ... additional PHP code ...
Opening braces for classes or methods MUST go on the next line
<?php class ClassName { public function sampleMethod($a, $b = null) { // method body } final public static function bar() { // method body } }
- Control structure keywords MUST have one space after them
- Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.
- Opening parentheses for control structures MUST NOT have a space after them, and closing parentheses for control structures MUST NOT have a space before.
if ($a === $b) { bar(); } elseif ($a > $b) { $foo->bar($arg1); } else { BazClass::bar($arg2, $arg3); }
class與function 和 ifelse的{}是不同的
Method arguments with default values MUST go at the end of the argument list.
<?php namespace Vendor\Package; class ClassName { public function foo($arg1, &$arg2, $arg3 = []) { // method body } }
See more in http://www.php-fig.org/