格式 ABCD
A: 編碼
1 用戶錯誤
2 網絡錯誤
3 系統錯誤
4 應用伺服器錯誤
5 應用程序錯誤
6 緩存錯誤
7 資料庫錯誤
8 搜索引擎
B 編碼
0 成功
1 失敗
剩餘 C D 用戶自行編碼
https://code.google.com/p/google-styleguide/ http://lxr.linux.no/linux/Documentation/CodingStyle http://perldoc.perl.org/perlstyle.html http://www.gnu.org/prep/standards/
http://www.php-fig.org
使用 UNIX 風格換行, 請在你的編輯器內調整
UNIX (LF或"\n") MAC OS (CR 或"\r") Windows CRLF \r\n
源碼檔案使用 UTF-8
有些IDE環境 UTF-8 BOM
if, while, for, foreach, do ... loop, switch... 等的嵌套必須小於等於3層
如下面的例子,可讀性極差。
if (xxx){ if (xxx){ if(xxx){ if(xxx){ if(xxx){ } } } if(xxx){ if(xxx){ } } } if (xxx){ if(xxx){ if(xxx){ } } if(xxx){ if(xxx){ } } } }
加以改造
func aaa(p){ if(p){ if(xxx){ } } } func bbb(b){ if(b){ if(xxx){ if(xxx){ } } } } if(xxx){ aaa(xxx) } if(b){ bbb(b) }
<?php /** * Project Name * * @author $Author: netkiller $ * @copyright Copyright (c) 2012 Company * @version $Id: chapter.coding.xml 584 2013-05-15 05:13:17Z netkiller $ */ <?php /** * Project Name * * @author $Author: netkiller $ * @license GNU General Public License 2.0 * @version $Id: chapter.coding.xml 584 2013-05-15 05:13:17Z netkiller $ */
雙引號要處理字元串轉義,性能上不如單引號,如果你不需要轉義字元串,或者字元串中不含原轉譯字元,建議你使用單引號
print("string")
每次輸出會檢索特殊字元串如: \r, \n, \t, \0xFF 等等
print('string')
使用pdo_mysql替代mysql
錯誤的寫法,通過字元串連結拼接sql語句極容易出現注入漏洞
$sql = "select * from table where id=".$id; $sql = "select * from table where id='".$id."'"; $sql = "INSERT INTO fruit(name, colour) VALUES ('".$name."', '".$colour."')";
正確的寫法
$sql = "select * from table where id=?"; $sql = "INSERT INTO fruit(name, colour) VALUES (?, ?)";
$sql = <<<____SQL CREATE TABLE IF NOT EXISTS `ticket_hist` ( `tid` int(11) NOT NULL, `trqform` varchar(40) NOT NULL, `trsform` varchar(40) NOT NULL, `tgen` datetime NOT NULL, `tterm` datetime, `tstatus` tinyint(1) NOT NULL ) ENGINE=ARCHIVE COMMENT='ticket archive'; ____SQL;
返回資料庫查詢結果有幾種形式
數組形式
Array ( [0] => banana [1] => yellow ) Array ( [NAME] => banana [COLOUR] => yellow )
對象形式
Object ( Obj->NAME Obj->COLOUR )
正確的使用方式
print($row[name]) print($row->name)
錯誤的使用使方式
print($row[0])
避免使用 "*"查詢,一會影響性能,二增加頻寬開銷
$sql = "select * from tab where status=0 limit 1";
如果程序使用$row[1]讀取結果,有可能當資料庫結構改變,增加欄位,欄位順序發生變化,輸出數據都會出錯
下面的例子,不會使用索引
$sql = "select id, name, created from tab where id != 100";
EXPLAIN select * from members where id != '1010'; 索引失效 EXPLAIN select count(*) from members where id != '1010'; 索引有效