PHP代碼樣式
如果使用第三方架構,並且有提供代碼樣式說明,則遵循其代碼樣式標準,否則如下!
== 格式:
* 使用UTF-8編碼
* 使用4個空格縮排,禁止使用Tab
* Unix樣式分行符號(LF)
* 在逗號、冒號和分號操作符使用空格
* 在 (,[ 後面、],) 前面不使用空格
* 在代碼塊中使用4個空格縮排
* 採用層級縮排
* 在return方法的傳回值前使用空行(除非只有一行代碼)以及在兩個方法中使用空行區分
* 在兩個大的邏輯程式碼片段之間使用空行區分
* 保持行字數在80字以內,最多不超過120
* 使用標準的PHP標籤定界,禁止使用短標籤(),對於只包含有PHP代碼的文
件,禁止使用PHP結束標誌("?>"),檔案末尾使用注釋說明"/* End of file */"
* 單行代碼也必須使用分號(;)結束
== 命名:
* 檔案名稱使用snake_case方式,禁止使用臃腫的檔案名稱
* 變數名使用snake_case方式,禁止使用臃腫的變數名
* 禁止使用單字元做為局部變數(如$i),在for迴圈中除外
* 禁止使用大寫字母做為全域變數,如使用大寫字母,應使用SCREAMING_SNAKE_CASE方式
* 類名使用CamelCase方式,方法名使用camelCase方式(保持像HTTP,RFC,XML縮寫詞的大寫)
* 常量名使用SCREAMING_SNAKE_CASE方式
// badsuperclass.phpSuperClass.phpsuperClass.php$i = "foobar"; // 單字元變數只充許使用在for迴圈中$bufferdText // 駝峰式變數,並且意思可以再精簡些$groupid // 兩個單詞之間需要底線分開$name_of_last_city_used // 太長MyConstant // 應該用底線並且字母沒有全大寫N // 單字元S_C_VER // 意思不清楚class superclassclass superClassfunction fileproperties() // 意思不清楚並且沒有駝峰式命名function fileProperties() // 意思不清楚function getfileproperties() // 好些了,但沒有駝峰式命名// goodsuper_class.phpfor ($i = 0; $i < 10; $i++)$buffer$group_id$last_cityMY_CONSTANTNEWLINESUPER_CLASS_VERSIONclass SuperClassfunction getFileProperties()
== 文法:
對於嵌入HTML中的PHP代碼,對於像if, for, foreach, while等代碼塊,採用if: ... endif; for: ... endfor; foreach: ... endforeach;以及 while: ... endwhile;方法塊
...isLoggedIn()): // checking logged in ?>...
== 注釋:
* 文檔塊必須和phpDocumentor格式相容,請參考: http://phpdoc.org/
* 避免多餘的意見
/** * 控制器類說明資訊 */class Controller { private static $instance; public function __construct() { ... } /** * 函數說明資訊 */ public static function &get_instance() { ... }/* End of file controller.php */
== 其他:
* 保持代碼簡單
* 保持一致性
參考:CodeIgniter,ZendFramework,Wordpress等
http://codeigniter.com/user_guide/general/styleguide.html
http://framework.zend.com/manual/zh/coding-standard.coding-style.html
http://codex.wordpress.org/WordPress_Coding_Standards
其他
Github https://github.com/styleguide
HTML/CSS 代碼樣式(英文)
http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml
Javascript 代碼樣式(英文)
http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
Ruby 樣式參見(英文) https://github.com/chneukirchen/styleguide/blob/master/RUBY-STYLE
1 樓 huawei2772 2012-02-17
好!