- 相關(guān)推薦
高質(zhì)量PHP代碼的50個(gè)實(shí)用技巧必備
文章主要為大家分享了50個(gè)高質(zhì)量PHP代碼的實(shí)用技巧,大家必備的php實(shí)用代碼,感興趣的小伙伴們可以參考一下。就跟隨百分網(wǎng)小編一起去了解下吧,想了解更多相關(guān)信息請持續關(guān)注我們應屆畢業(yè)生考試網(wǎng)!
1.不要使用相對路徑
常常會(huì )看到:
?
1
require_once('../../lib/some_class.php');
該方法有很多缺點(diǎn): 它首先查找指定的php包含路徑, 然后查找當前目錄。因此會(huì )檢查過(guò)多路徑。如果該腳本被另一目錄的腳本包含, 它的基本目錄變成了另一腳本所在的目錄.
另一問(wèn)題, 當定時(shí)任務(wù)運行該腳本, 它的上級目錄可能就不是工作目錄了。因此最佳選擇是使用絕對路徑:
?
1
2
3
4
view sourceprint?
define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');
//rest of the code
我們定義了一個(gè)絕對路徑, 值被寫(xiě)死了. 我們還可以改進(jìn)它. 路徑 /var/www/project 也可能會(huì )改變, 那么我們每次都要改變它嗎? 不是的, 我們可以使用__FILE__常量, 如:
?
1
2
3
4
5
//suppose your script is /var/www/project/index.php
//Then __FILE__ will always have that full path.
define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_class.php');
//rest of the code
現在, 無(wú)論你移到哪個(gè)目錄, 如移到一個(gè)外網(wǎng)的服務(wù)器上, 代碼無(wú)須更改便可正確運行.
2. 不要直接使用 require, include, include_once, required_once
可以在腳本頭部引入多個(gè)文件, 像類(lèi)庫, 工具文件和助手函數等, 如:
?
1
2
3
require_once('lib/Database.php');
require_once('lib/Mail.php');
require_once('helpers/utitlity_functions.php');
這種用法相當原始. 應該更靈活點(diǎn). 應編寫(xiě)個(gè)助手函數包含文件. 例如:
?
1
2
3
4
5
6
7
8
function load_class($class_name)
{
//path to the class file
$path = ROOT . '/lib/' . $class_name . '.php');
require_once( $path );
}
load_class('Database');
load_class('Mail');
有什么不一樣嗎? 該代碼更具可讀性。將來(lái)你可以按需擴展該函數, 如:
?
1
2
3
4
5
6
7
8
9
function load_class($class_name)
{
//path to the class file
$path = ROOT . '/lib/' . $class_name . '.php');
if(file_exists($path))
{
require_once( $path );
}
}
還可做得更多: 為同樣文件查找多個(gè)目錄。能很容易的改變放置類(lèi)文件的目錄, 無(wú)須在代碼各處一一修改?墒褂妙(lèi)似的函數加載文件, 如html內容.
3. 為應用保留調試代碼
在開(kāi)發(fā)環(huán)境中, 我們打印數據庫查詢(xún)語(yǔ)句, 轉存有問(wèn)題的變量值, 而一旦問(wèn)題解決, 我們注釋或刪除它們. 然而更好的做法是保留調試代碼。在開(kāi)發(fā)環(huán)境中, 你可以:
?
1
2
3
4
5
6
7
8
9
10
11
12
define('ENVIRONMENT' , 'development');
if(! $db->query( $query )
{
if(ENVIRONMENT == 'development')
{
echo "$query failed";
}
else
{
echo "Database error. Please contact administrator";
}
}
在服務(wù)器中, 你可以:
?
1
2
3
4
5
6
7
8
9
10
11
12
define('ENVIRONMENT' , 'production');
if(! $db->query( $query )
{
if(ENVIRONMENT == 'development')
{
echo "$query failed";
}
else
{
echo "Database error. Please contact administrator";
}
}
4. 使用可跨平臺的函數執行命令
system, exec, passthru, shell_exec 這4個(gè)函數可用于執行系統命令. 每個(gè)的行為都有細微差別. 問(wèn)題在于, 當在共享主機中, 某些函數可能被選擇性的禁用. 大多數新手趨于每次首先檢查哪個(gè)函數可用, 然而再使用它。更好的方案是封成函數一個(gè)可跨平臺的函數.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
Method to execute a command in the terminal
Uses :
1. system
2. passthru
3. exec
4. shell_exec
*/
function terminal($command)
{
//system
if(function_exists('system'))
{
ob_start();
system($command , $return_var);
$output = ob_get_contents();
ob_end_clean();
}
//passthru
else if(function_exists('passthru'))
{
ob_start();
passthru($command , $return_var);
$output = ob_get_contents();
ob_end_clean();
}
//exec
else if(function_exists('exec'))
{
exec($command , $output , $return_var);
$output = implode("\n" , $output);
}
//shell_exec
else if(function_exists('shell_exec'))
{
$output = shell_exec($command) ;
}
else
{
$output = 'Command execution not possible on this system';
$return_var = 1;
}
return array('output' => $output , 'status' => $return_var);
}
terminal('ls');
上面的函數將運行shell命令, 只要有一個(gè)系統函數可用, 這保持了代碼的一致性.
5. 靈活編寫(xiě)函數
?
1
2
3
4
5
6
function add_to_cart($item_id , $qty)
{
$_SESSION['cart']['item_id'] = $qty;
}
add_to_cart( 'IPHONE3' , 2 );
使用上面的函數添加單個(gè)項目. 而當添加項列表的時(shí)候,你要創(chuàng )建另一個(gè)函數嗎? 不用, 只要稍加留意不同類(lèi)型的參數, 就會(huì )更靈活. 如:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function add_to_cart($item_id , $qty)
{
if(!is_array($item_id))
{
$_SESSION['cart']['item_id'] = $qty;
}
else
{
foreach($item_id as $i_id => $qty)
{
$_SESSION['cart']['i_id'] = $qty;
}
}
}
add_to_cart( 'IPHONE3' , 2 );
add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );
現在, 同個(gè)函數可以處理不同類(lèi)型的輸入參數了. 可以參照上面的例子重構你的多處代碼, 使其更智能.
6. 有意忽略php關(guān)閉標簽
我很想知道為什么這么多關(guān)于php建議的博客文章都沒(méi)提到這點(diǎn).
?
1
2
3
<?php
echo "Hello";
//Now dont close this tag
這將節約你很多時(shí)間. 我們舉個(gè)例子:
一個(gè) super_class.php 文件
?
1
2
3
4
5
6
7
8
9
<?php
class super_class
{
function super_function()
{
//super code
}
}
?>
//super extra character after the closing tag
index.php
?
1
2
require_once('super_class.php');
//echo an image or pdf , or set the cookies or session data
這樣, 你將會(huì )得到一個(gè) Headers already send error. 為什么? 因為 “super extra character” 已經(jīng)被輸出了. 現在你得開(kāi)始調試啦. 這會(huì )花費大量時(shí)間尋找 super extra 的位置。因此, 養成省略關(guān)閉符的習慣:
?
1
2
3
4
5
6
7
8
9
<?php
class super_class
{
function super_function()
{
//super code
}
}
//No closing tag
這會(huì )更好.
7. 在某地方收集所有輸入, 一次輸出給瀏覽器
這稱(chēng)為輸出緩沖, 假如說(shuō)你已在不同的函數輸出內容:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function print_header()
{
echo "<p id='header'>Site Log and Login links</p>";
}
function print_footer()
{
echo "<p id='footer'>Site was made by me</p>";
}
print_header();
for($i = 0 ; $i < 100; $i++)
{
echo "I is : $i ';
}
print_footer();
替代方案, 在某地方集中收集輸出. 你可以存儲在函數的局部變量中, 也可以使用ob_start和ob_end_clean. 如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function print_header()
{
$o = "<p id='header'>Site Log and Login links</p>";
return $o;
}
function print_footer()
{
$o = "<p id='footer'>Site was made by me</p>";
return $o;
}
echo print_header();
for($i = 0 ; $i < 100; $i++)
{
echo "I is : $i ';
}
echo print_footer();
為什么需要輸出緩沖:
>>可以在發(fā)送給瀏覽器前更改輸出. 如 str_replaces 函數或可能是 preg_replaces 或添加些監控/調試的html內容.
>>輸出給瀏覽器的同時(shí)又做php的處理很糟糕. 你應該看到過(guò)有些站點(diǎn)的側邊欄或中間出現錯誤信息. 知道為什么會(huì )發(fā)生嗎? 因為處理和輸出混合了.
8. 發(fā)送正確的mime類(lèi)型頭信息, 如果輸出非html內容的話(huà).
輸出一些xml.
?
1
2
3
4
5
6
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
$xml = "<response>
<code>0</code>
</response>";
//Send xml data
echo $xml;
工作得不錯. 但需要一些改進(jìn).
?
1
2
3
4
5
6
7
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
$xml = "<response>
<code>0</code>
</response>";
//Send xml data
header("content-type: text/xml");
echo $xml;
注意header行. 該行告知瀏覽器發(fā)送的是xml類(lèi)型的內容. 所以瀏覽器能正確的處理. 很多的javascript庫也依賴(lài)頭信息.
類(lèi)似的有 javascript , css, jpg image, png image:
?
1
2
3
4
5
6
JavaScript
header("content-type: application/x-javascript");
echo "var a = 10";
CSS
header("content-type: text/css");
echo "#p id { background:#000; }";
9. 為mysql連接設置正確的字符編碼
曾經(jīng)遇到過(guò)在mysql表中設置了unicode/utf-8編碼, phpadmin也能正確顯示, 但當你獲取內容并在頁(yè)面輸出的時(shí)候,會(huì )出現亂碼. 這里的問(wèn)題出在mysql連接的字符編碼.
?
1
2
3
4
5
6
7
8
9
10
11
12
//Attempt to connect to database
$c = mysqli_connect($this->host , $this->username, $this->password);
//Check connection validity
if (!$c)
{
die ("Could not connect to the database host: ". mysqli_connect_error());
}
//Set the character set of the connection
if(!mysqli_set_charset ( $c , 'UTF8' ))
{
die('mysqli_set_charset() failed');
}
一旦連接數據庫, 最好設置連接的 characterset. 你的應用如果要支持多語(yǔ)言, 這么做是必須的.
10. 使用 htmlentities 設置正確的編碼選項
php5.4前, 字符的默認編碼是ISO-8859-1, 不能直接輸出如? ?等.
?
1
$value = htmlentities($this->value , ENT_QUOTES , CHARSET);
php5.4以后, 默認編碼為UTF-8, 這將解決很多問(wèn)題. 但如果你的應用是多語(yǔ)言的, 仍然要留意編碼問(wèn)題,.
11. 不要在應用中使用gzip壓縮輸出, 讓apache處理
考慮過(guò)使用 ob_gzhandler 嗎? 不要那樣做. 毫無(wú)意義. php只應用來(lái)編寫(xiě)應用. 不應操心服務(wù)器和瀏覽器的數據傳輸優(yōu)化問(wèn)題.
使用apache的mod_gzip/mod_deflate 模塊壓縮內容.
12. 使用json_encode輸出動(dòng)態(tài)javascript內容
時(shí)常會(huì )用php輸出動(dòng)態(tài)javascript內容:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$images = array(
'myself.png' , 'friends.png' , 'colleagues.png'
);
$js_code = '';
foreach($images as $image)
{
$js_code .= "'$image' ,";
}
$js_code = 'var images = [' . $js_code . ']; ';
echo $js_code;
//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];
更聰明的做法, 使用 json_encode:
$images = array(
'myself.png' , 'friends.png' , 'colleagues.png'
);
$js_code = 'var images = ' . json_encode($images);
echo $js_code;
//Output is : var images = ["myself.png","friends.png","colleagues.png"]
優(yōu)雅乎?
13. 寫(xiě)文件前, 檢查目錄寫(xiě)權限
寫(xiě)或保存文件前, 確保目錄是可寫(xiě)的, 假如不可寫(xiě), 輸出錯誤信息. 這會(huì )節約你很多調試時(shí)間. linux系統中, 需要處理權限, 目錄權限不當會(huì )導致很多很多的問(wèn)題, 文件也有可能無(wú)法讀取等等.
確保你的應用足夠智能, 輸出某些重要信息.
?
1
2
3
$contents = "All the content";
$file_path = "/var/www/project/content.txt";
file_put_contents($file_path , $contents);
這大體上正確. 但有些間接的問(wèn)題. file_put_contents 可能會(huì )由于幾個(gè)原因失敗:
>>父目錄不存在
>>目錄存在, 但不可寫(xiě)
>>文件被寫(xiě)鎖住?
所以寫(xiě)文件前做明確的檢查更好.
?
1
2
3
4
5
6
7
8
9
10
11
$contents = "All the content";
$dir = '/var/www/project';
$file_path = $dir . "/content.txt";
if(is_writable($dir))
{
file_put_contents($file_path , $contents);
}
else
{
die("Directory $dir is not writable, or does not exist. Please check");
}
這么做后, 你會(huì )得到一個(gè)文件在何處寫(xiě)及為什么失敗的明確信息.
14. 更改應用創(chuàng )建的文件權限
在linux環(huán)境中, 權限問(wèn)題可能會(huì )浪費你很多時(shí)間. 從今往后, 無(wú)論何時(shí), 當你創(chuàng )建一些文件后, 確保使用chmod設置正確權限. 否則的話(huà), 可能文件先是由”php”用戶(hù)創(chuàng )建, 但你用其它的用戶(hù)登錄工作, 系統將會(huì )拒絕訪(fǎng)問(wèn)或打開(kāi)文件, 你不得不奮力獲取root權限, 更改文件的權限等等.
?
1
2
3
4
// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);
15. 不要依賴(lài)submit按鈕值來(lái)檢查表單提交行為
?
1
2
3
4
if($_POST['submit'] == 'Save')
{
//Save the things
}
上面大多數情況正確, 除了應用是多語(yǔ)言的. ‘Save' 可能代表其它含義. 你怎么區分它們呢. 因此, 不要依賴(lài)于submit按鈕的值.
?
1
2
3
4
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
{
//Save the things
}
現在你從submit按鈕值中解脫出來(lái)了.
16. 為函數內總具有相同值的變量定義成靜態(tài)變量
?
1
2
3
4
5
6
7
8
//Delay for some time
function delay()
{
$sync_delay = get_option('sync_delay');
echo "Delaying for $sync_delay seconds...";
sleep($sync_delay);
echo "Done ";
}
用靜態(tài)變量取代:
?
1
2
3
4
5
6
7
8
9
10
11
12
//Delay for some time
function delay()
{
static $sync_delay = null;
if($sync_delay == null)
{
$sync_delay = get_option('sync_delay');
}
echo "Delaying for $sync_delay seconds...";
sleep($sync_delay);
echo "Done ";
}
17. 不要直接使用 $_SESSION 變量
某些簡(jiǎn)單例子:
?
1
2
$_SESSION['username'] = $username;
$username = $_SESSION['username'];
這會(huì )導致某些問(wèn)題. 如果在同個(gè)域名中運行了多個(gè)應用, session 變量可能會(huì )沖突. 兩個(gè)不同的應用可能使用同一個(gè)session key. 例如, 一個(gè)前端門(mén)戶(hù), 和一個(gè)后臺管理系統使用同一域名。從現在開(kāi)始, 使用應用相關(guān)的key和一個(gè)包裝函數:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
define('APP_ID' , 'abc_corp_ecommerce');
//Function to get a session variable
function session_get($key)
{
$k = APP_ID . '.' . $key;
if(isset($_SESSION[$k]))
{
return $_SESSION[$k];
}
return false;
}
//Function set the session variable
function session_set($key , $value)
{
$k = APP_ID . '.' . $key;
$_SESSION[$k] = $value;
return true;
}
18. 將工具函數封裝到類(lèi)中
假如你在某文件中定義了很多工具函數:
?
1
2
3
4
5
6
7
8
9
10
11
12
function utility_a()
{
//This function does a utility thing like string processing
}
function utility_b()
{
//This function does nother utility thing like database processing
}
function utility_c()
{
//This function is ...
}
這些函數的使用分散到應用各處. 你可能想將他們封裝到某個(gè)類(lèi)中:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Utility
{
public static function utility_a()
{
}
public static function utility_b()
{
}
public static function utility_c()
{
}
}
//and call them as
$a = Utility::utility_a();
$b = Utility::utility_b();
顯而易見(jiàn)的好處是, 如果php內建有同名的函數, 這樣可以避免沖突.
另一種看法是, 你可以在同個(gè)應用中為同個(gè)類(lèi)維護多個(gè)版本, 而不導致沖突. 這是封裝的基本好處, 無(wú)它.
19. Bunch of silly tips
>>使用echo取代print
>>使用str_replace取代preg_replace, 除非你絕對需要
>>不要使用 short tag
>>簡(jiǎn)單字符串用單引號取代雙引號
>>head重定向后記得使用exit
>>不要在循環(huán)中調用函數
>>isset比strlen快
>>始中如一的格式化代碼
>>不要刪除循環(huán)或者if-else的括號
不要這樣寫(xiě)代碼:
?
1
<span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">if($a == true) $a_count++;</span>
這絕對WASTE。寫(xiě)成:
?
1
2
3
4
<span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">if($a == true)
{
$a_count++;
}</span>
不要嘗試省略一些語(yǔ)法來(lái)縮短代碼. 而是讓你的邏輯簡(jiǎn)短.
>>使用有高亮語(yǔ)法顯示的文本編輯器. 高亮語(yǔ)法能讓你減少錯誤.
20. 使用array_map快速處理數組
比如說(shuō)你想 trim 數組中的所有元素. 新手可能會(huì ):
?
1
2
3
4
foreach($arr as $c => $v)
{
$arr[$c] = trim($v);
}
但使用 array_map 更簡(jiǎn)單:
?
1
$arr = array_map('trim' , $arr);
這會(huì )為$arr數組的每個(gè)元素都申請調用trim. 另一個(gè)類(lèi)似的函數是 array_walk. 請查閱文檔學(xué)習更多技巧.
21. 使用 php filter 驗證數據
你肯定曾使用過(guò)正則表達式驗證 email , ip地址等. 是的,每個(gè)人都這么使用. 現在, 我們想做不同的嘗試, 稱(chēng)為filter.
php的filter擴展提供了簡(jiǎn)單的方式驗證和檢查輸入.
22. 強制類(lèi)型檢查
?
1
2
$amount = intval( $_GET['amount'] );
$rate = (int) $_GET['rate'];
這是個(gè)好習慣.
23. 如果需要,使用profiler如xdebug
如果你使用php開(kāi)發(fā)大型的應用, php承擔了很多運算量, 速度會(huì )是一個(gè)很重要的指標. 使用profile幫助優(yōu)化代碼. 可使用xdebug和webgrid.
24. 小心處理大數組
對于大的數組和字符串, 必須小心處理. 常見(jiàn)錯誤是發(fā)生數組拷貝導致內存溢出,拋出Fatal Error of Memory size 信息:
?
1
2
3
$db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB
$cc = $db_records_in_array_format; //2MB more
some_function($cc); //Another 2MB ?
當導入或導出csv文件時(shí), 常常會(huì )這么做。不要認為上面的代碼會(huì )經(jīng)常因內存限制導致腳本崩潰. 對于小的變量是沒(méi)問(wèn)題的, 但處理大數組的時(shí)候就必須避免.
確保通過(guò)引用傳遞, 或存儲在類(lèi)變量中:
?
1
2
$a = get_large_array();
pass_to_function(&$a);
這么做后, 向函數傳遞變量引用(而不是拷貝數組). 查看文檔.
?
1
2
3
4
5
6
7
8
9
10
11
12
class A
{
function first()
{
$this->a = get_large_array();
$this->pass_to_function();
}
function pass_to_function()
{
//process $this->a
}
}
盡快的 unset 它們, 讓內存得以釋放,減輕腳本負擔.
25. 由始至終使用單一數據庫連接
確保你的腳本由始至終都使用單一的數據庫連接. 在開(kāi)始處正確的打開(kāi)連接, 使用它直到結束, 最后關(guān)閉它. 不要像下面這樣在函數中打開(kāi)連接:
?
1
2
3
4
5
6
7
8
9
10
function add_to_cart()
{
$db = new Database();
$db->query("INSERT INTO cart .....");
}
function empty_cart()
{
$db = new Database();
$db->query("DELETE FROM cart .....");
}
使用多個(gè)連接是個(gè)糟糕的, 它們會(huì )拖慢應用, 因為創(chuàng )建連接需要時(shí)間和占用內存。特定情況使用單例模式, 如數據庫連接.。
這個(gè)秘籍是不是很精彩,相信一定對大家學(xué)習php程序設計有所幫助。
【高質(zhì)量PHP代碼的50個(gè)技巧】相關(guān)文章:
PHP代碼優(yōu)化技巧09-10
提高PHP代碼質(zhì)量的技巧08-31
PHP調用的C代碼技巧06-27
20條PHP代碼優(yōu)化技巧05-24
PHP實(shí)用的代碼實(shí)例08-12
php分頁(yè)類(lèi)代碼09-08
PHP調用的C代碼08-05
PHP代碼運行流程08-14
PHP代碼如何規范08-28