- 相關(guān)推薦
對(duì)初學(xué)者非常有用的PHP技巧
文章主要為大家詳細(xì)介紹了10個(gè)對(duì)初學(xué)者非常有用的PHP技巧,這些PHP技巧適用于初學(xué)者,而不是那些已經(jīng)在使用MVC框架的人,感興趣的小伙伴們可以參考一下。
本文介紹一些關(guān)于改善和優(yōu)化PHP代碼的提示和技巧,供大家參考,具體內(nèi)容如下
1.不要使用相對(duì)路徑,要定義一個(gè)根路徑
這樣的代碼行很常見:
?
1
require_once('../../lib/some_class.php');
這種方法有很多缺點(diǎn):
1)、它首先搜索php包括路徑中的指定目錄,然后查看當(dāng)前目錄。因此,會(huì)檢查許多目錄。
2)、當(dāng)一個(gè)腳本被包含在另一個(gè)腳本的不同目錄中時(shí),它的基本目錄變?yōu)榘_本的目錄。
3)、另一個(gè)問題是,當(dāng)一個(gè)腳本從cron運(yùn)行時(shí),它可能不會(huì)將它的父目錄作為工作目錄。
所以使用絕對(duì)路徑便成為了一個(gè)好方法:
?
1
2
3
4
define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');
//rest of the code
這就是一個(gè)絕對(duì)路徑,并且會(huì)一直保持不變。但是,我們可以進(jìn)一步改善。目錄/var/www/project可以變,那么我們每次都要改嗎?
不,使用魔術(shù)常量如__FILE__可以讓它變得可移植。請(qǐng)仔細(xì)看:
?
1
2
3
4
5
6
7
//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
所以現(xiàn)在,即使你將項(xiàng)目轉(zhuǎn)移到一個(gè)不同的目錄,例如將其移動(dòng)到一個(gè)在線的服務(wù)器上,這些代碼不需要更改就可以運(yùn)行。
2.不使用require,包括require_once或include_once
你的腳本上可能會(huì)包括各種文件,如類庫(kù),實(shí)用程序文件和輔助函數(shù)等,就像這些:
?
1
2
3
4
require_once('lib/Database.php');
require_once('lib/Mail.php');
require_once('helpers/utitlity_functions.php');
這相當(dāng)粗糙。代碼需要更加靈活。寫好輔助函數(shù)可以更容易地包含東西。舉個(gè)例子:
?
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');
require_once( $path );
}
load_class('Database');
load_class('Mail');
看到區(qū)別了嗎?很明顯。不需要任何更多的解釋。
你還可以進(jìn)一步改善:
?
1
2
3
4
5
6
7
8
9
10
function load_class($class_name)
{
//path to the class file
$path = ROOT . '/lib/' . $class_name . '.php');
if(file_exists($path))
{
require_once( $path );
}
}
這樣做可以完成很多事情:
為同一個(gè)類文件搜索多個(gè)目錄。
輕松更改包含類文件的目錄,而不破壞任何地方的代碼。
使用類似的函數(shù)用于加載包含輔助函數(shù)、HTML內(nèi)容等的文件。
3.在應(yīng)用程序中維護(hù)調(diào)試環(huán)境
在開發(fā)過程中,我們echo數(shù)據(jù)庫(kù)查詢,轉(zhuǎn)儲(chǔ)創(chuàng)造問題的變量,然后一旦問題被解決,我們注釋它們或刪除它們。但讓一切留在原地可提供長(zhǎng)效幫助。
在開發(fā)計(jì)算機(jī)上,你可以這樣做:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
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
13
define('ENVIRONMENT' , 'production');
if(! $db->query( $query )
{
if(ENVIRONMENT == 'development')
{
echo "$query failed";
}
else
{
echo "Database error. Please contact administrator";
}
}
4.通過會(huì)話傳播狀態(tài)消息
狀態(tài)消息是那些執(zhí)行任務(wù)后生成的消息。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
if($wrong_username || $wrong_password)
{
$msg = 'Invalid username or password';
}
?>
<html>
<body>
<?php echo $msg; ?>
<form>
...
</form>
</body>
</html>
這樣的代碼很常見。使用變量來顯示狀態(tài)信息有一定的局限性。因?yàn)樗鼈儫o法通過重定向發(fā)送(除非你將它們作為GET變量傳播給下一個(gè)腳本,但這非常愚蠢)。而且在大型腳本中可能會(huì)有多個(gè)消息等。
最好的辦法是使用會(huì)話來傳播(即使是在同一頁(yè)面上)。想要這樣做的話在每個(gè)頁(yè)面上必須得有一個(gè)session_start。
?
1
2
3
4
5
6
7
8
9
10
11
function set_flash($msg)
{
$_SESSION['message'] = $msg;
}
function get_flash()
{
$msg = $_SESSION['message'];
unset($_SESSION['message']);
return $msg;
}
在你的腳本中:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
if($wrong_username || $wrong_password)
{
set_flash('Invalid username or password');
}
?>
<html>
<body>
Status is : <?php echo get_flash(); ?>
<form>
...
</form>
</body>
</html>
5.讓函數(shù)變得靈活
?
1
2
3
4
5
6
function add_to_cart($item_id , $qty)
{
$_SESSION['cart'][$item_id] = $qty;
}
add_to_cart( 'IPHONE3' , 2 );
當(dāng)添加單一條目時(shí),使用上面的函數(shù)。那么當(dāng)添加多個(gè)條目時(shí),就得創(chuàng)建另一個(gè)函數(shù)嗎?NO。只要讓函數(shù)變得靈活起來使之能夠接受不同的參數(shù)即可。請(qǐng)看:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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) );
好了,現(xiàn)在同樣的函數(shù)就可以接受不同類型的輸出了。以上代碼可以應(yīng)用到很多地方讓你的代碼更加靈活。
6.省略結(jié)束的php標(biāo)簽,如果它是腳本中的最后一行
我不知道為什么很多博客文章在談?wù)損hp小技巧時(shí)要省略這個(gè)技巧。
?
1
2
3
4
5
<?php
echo "Hello";
//Now dont close this tag
這可以幫助你省略大量問題。舉一個(gè)例子:
類文件super_class.php
?
1
2
3
4
5
6
7
8
9
10
<?php
class super_class
{
function super_function()
{
//super code
}
}
?>
//super extra character after the closing tag
現(xiàn)在看index.php
?
1
2
3
require_once('super_class.php');
//echo an image or pdf , or set the cookies or session data
你會(huì)得到發(fā)送錯(cuò)誤的Header。為什么呢?因?yàn)?ldquo;超級(jí)多余字符”,所有標(biāo)題都去處理這個(gè)去了。于是你得開始調(diào)試。你可能需要浪費(fèi)很多時(shí)間來尋找超級(jí)額外的空間。
因此要養(yǎng)成省略結(jié)束標(biāo)簽的習(xí)慣:
?
1
2
3
4
5
6
7
8
9
10
<?php
class super_class
{
function super_function()
{
//super code
}
}
//No closing tag
這樣更好。
7.在一個(gè)地方收集所有輸出,然后一次性輸出給瀏覽器
這就是所謂的輸出緩沖。比方說,你從不同的函數(shù)得到像這樣的內(nèi)容:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 <br />';
}
print_footer();
其實(shí)你應(yīng)該先在一個(gè)地方收集所有輸出。你可以要么將它存儲(chǔ)于函數(shù)中的變量?jī)?nèi)部,要么使用ob_start和ob_end_clean。所以,現(xiàn)在應(yīng)該看起來像這樣
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 <br />';
}
echo print_footer();
那么,為什么你應(yīng)該做輸出緩沖呢:
你可以在將輸出發(fā)送給瀏覽器之前更改它,如果你需要的話。例如做一些str_replaces,或者preg_replaces,又或者是在末尾添加一些額外的html,例如profiler/debugger輸出。
發(fā)送輸出給瀏覽器,并在同一時(shí)間做php處理并不是好主意。你見過這樣的網(wǎng)站,它有一個(gè)Fatal error在側(cè)邊欄或在屏幕中間的方框中嗎?你知道為什么會(huì)出現(xiàn)這種情況嗎?因?yàn)樘幚磉^程和輸出被混合在了一起。
8.當(dāng)輸出非HTML內(nèi)容時(shí),通過header發(fā)送正確的mime類型
請(qǐng)看一些XML。
?
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
echo $xml;
工作正常。但它需要一些改進(jìn)。
?
1
2
3
4
5
6
7
8
$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;
請(qǐng)注意header行。這行代碼告訴瀏覽器這個(gè)內(nèi)容是XML內(nèi)容。因此,瀏覽器能夠正確地處理它。許多JavaScript庫(kù)也都依賴于header信息。
JavaScript,css,jpg圖片,png圖像也是一樣:
JavaScript
?
1
2
3
4
5
6
header("content-type: application/x-javascript");
echo "var a = 10";
CSS
header("content-type: text/css");
echo "#p id { background:#000; }"
9.為MySQL連接設(shè)置正確的字符編碼
曾碰到過unicode/utf-8字符被正確地存儲(chǔ)在mysql表的問題,phpmyadmin也顯示它們是正確的,但是當(dāng)你使用的時(shí)候,你的網(wǎng)頁(yè)上卻并不能正確地顯示。里面的奧妙在于MySQL連接校對(duì)。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$host = 'localhost';
$username = 'root';
$password = 'super_secret';
//Attempt to connect to database
$c = mysqli_connect($host , $username, $password);
//Check connection validity
if (!$c)
{
die ("Could not connect to the database host: <br />". mysqli_connect_error());
}
//Set the character set of the connection
if(!mysqli_set_charset ( $c , 'UTF8' ))
{
die('mysqli_set_charset() failed');
}
一旦你連接到數(shù)據(jù)庫(kù),不妨設(shè)置連接字符集。當(dāng)你在你的應(yīng)用程序中使用多種語(yǔ)言時(shí),這絕對(duì)有必要。
否則會(huì)發(fā)生什么呢?你會(huì)在非英文文本中看到很多的方框和????????。
10.使用帶有正確字符集選項(xiàng)的htmlentities
PHP 5.4之前,使用的默認(rèn)字符編碼是ISO-8859-1,這不能顯示例如? ? 這樣的字符。
?
1
$value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');
從PHP 5.4起,默認(rèn)編碼成了UTF-8,這解決了大部分的問題,但你最好還是知道這件事,如果你的應(yīng)用程序使用多種語(yǔ)言的話。
【對(duì)初學(xué)者非常有用的PHP技巧】相關(guān)文章:
PHP初學(xué)者必備的技能04-14
5個(gè)超級(jí)有用的php片段06-05
適合PHP初學(xué)者閱讀的經(jīng)典書籍07-07
PHP初學(xué)者頭疼問題匯總06-13
幾個(gè)php技巧04-20
PHP小技巧07-12
PHP初學(xué)者入門基礎(chǔ)知識(shí)03-25