首頁 後端開發 php教程 9個必須掌握的實用PHP函數與功能

9個必須掌握的實用PHP函數與功能

Jul 25, 2016 am 08:46 AM

本文出拓勝科技,請追蹤我的微信toceansoft

即使使用 PHP 多年,也會偶然發現一些未曾了解的函數和功能。其中有些是非常有用的,但沒有充分利用。並不是所有人都會從頭到尾一頁一頁地閱讀手冊和函數參考!
1、任意參數數目的函數
你可能已經知道,PHP 允許定義可選參數的函數。但也有完全允許任意數目的函數參數的方法。以下是選用參數的範例:
// function with 2 optional arguments
function foo($arg1 = ”, $arg2 = ”) {
echo “arg1: $arg1n”;
echo “arg2: $arg2n”;
}
foo(‘hello’,'world’);
/* prints:
arg1: hello
arg2: world
*/
foo();
/* prints:
arg1:
arg2:
*/
現在讓我們看看如何建立能夠接受任何參數數目的函數。這次需要使用 func_get_args() 函式:
// yes, the argument list can be empty
function foo() {
// returns an array of all passed arguments
$args = func_get_args();
foreach ($args as $k => $v) {
echo “arg”.($k 1).”: $vn”;
}
}
foo();
/* prints nothing */
foo(‘hello’);
/* prints
arg1: hello
*/
foo(‘hello’, ‘world’, ‘again’);
/* prints
arg1: hello
arg2: world
arg3: again
*/
2、使用 Glob() 尋找檔案
許多 PHP 函數具有長描述性的名稱。然而可能會很難說出 glob() 函數能做的事情,除非你已經通過多次使用並熟悉了它。可以把它看作是比 scandir() 函數更強大的版本,可以按照某種模式搜尋檔案。
// get all php files
$files = glob(‘*.php’);
print_r($files);
/* output looks like:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
你可以這樣取得多個檔案:
// get all php files AND txt files
$files = glob(‘*.{php,txt}’, GLOB_BRACE);
print_r($files);
/* output looks like:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
[4] => log.txt
[5] => test.txt
)
*/
請注意,這些檔案其實是可以回傳一條路徑,這取決於查詢條件:
$files = glob('../images/a*.jpg');
print_r($files);
/* output looks like:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
如果你想要取得每個檔案的完整路徑,你可以呼叫realpath() 函數:
$files = glob('../images/a*.jpg') ;
// applies the function to each array element
$files = array_map(‘realpath’,$files);
print_r($files);
/* output looks like:
Array
(
[0] => C:wampwwwimagesapple.jpg
[1] => C:wampwwwimagesart.jpg
)
*/
3、記憶體使用資訊
透過偵測腳本的記憶體使用情況,有利於程式碼的最佳化。 PHP 提供了一個垃圾收集器和一個非常複雜的記憶體管理器。腳本執行時所使用的記憶體量,有升有跌。為了得到目前的記憶體使用情況,我們可以使用 memory_get_usage() 函數。如果需要獲得任意時間點的最高記憶體使用量,則可以使用 memory_limit() 函數。
echo “Initial: “.memory_get_usage().” bytes n”;
/* prints
Initial: 361400 bytes
*/
// let’s use up some memory
for ($i = 0; $i $array []= md5($i);
}
// let’s remove half of the array
for ($i = 0; $i unset($array[$i]);
}
echo “Final: “.memory_get_usage().” bytes n”;
/* prints
Final: 885912 bytes
*/
echo “Peak: “.memory_get_peak_usage().” bytes n”;
/* prints
Peak: 13687072 bytes
*/
4、CPU 使用資訊
為此,我們要利用 getrusage() 函數。請記住這個函數不適用於 Windows 平台。
print_r(getrusage());
/* prints
Array
(
[ru_oublock] => 0
[ru_inblock] => 0
[ru_msgsnd] => 2
[ru_msgrcv] => 3
[ru_maxrss] => 12692
[ru_ixrss] => 764
[ru_idrss] => 3864
[ru_minflt] => 94
[ru_majflt] => 0
[ru_nsignals] => 1
[ru_nvcsw] => 67
[ru_nivcsw] => 4
[ru_nswap] => 0
[ru_utime.tv_usec] => 0
[ru_utime.tv_sec] => 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_sec] => 0
)
*/
這可能看起來有點神秘,除非你已經有系統管理員權限。以下是每個值的具體說明(你不需要記住這些):
ru_oublock: block output operations
ru_inblock: block input operations
ru_msgsnd: messages sent
ru_msgrcv: messages received
ru_maxrss: maximum resident set size
ru_ixrss: integral shared memory size
ru_idrss: integral unshared data size
ru_minflt: page reclaims
ru_majflt: page faults
ru_nsignals: signals received
ru_nvcsw: voluntary context switches
ru_nivcsw: involuntary context switches
ru_nswap: swaps
ru_utime.tv_usec: user time used (microseconds)
ru_utime.tv_sec: user time used (seconds)
ru_stime.tv_usec: system time used (microseconds)
ru_stime.tv_sec: system time used (seconds)
要知道腳本消耗多少 CPU 功率,我們需要看看 ‘user time’ 和’system time’ 兩個參數的值。秒和微秒部分預設是單獨提供的。你可以除以 100 萬微秒,並加上秒的參數值,得到一個十進制的總秒數。讓我們來看一個例子:
// sleep for 3 seconds (non-busy)
sleep(3);
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec']
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec']
$data['ru_stime.tv_usec'] / 1000000);
/* prints
User time: 0.011552
System time: 0
*/
儘管腳本運作花了大約 3 秒鐘,CPU 使用率卻非常非常低。因為在睡眠運作的過程中,該腳本實際上不消耗 CPU 資源。還有許多其他的任務,可能需要一段時間,但不佔用類似等待磁碟操作等 CPU 時間。因此正如你所看到的,CPU 使用率和運行時間的實際長度並不總是相同的。以下是一個例子:
// loop 10 million times (busy)
for($i=0;$i
}
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec']
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec']
$data['ru_stime.tv_usec'] / 1000000);
/* prints
User time: 1.424592
System time: 0.004204
*/
這花了大約 1.4 秒的 CPU 時間,但幾乎都是使用者時間,因為沒有系統呼叫。系統時間是指花費在執行程式的系統呼叫時的 CPU 開銷。下面是一個例子:
$start = microtime(true);
// keep calling microtime for about 3 seconds
while(microtime(true) – $start
}
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec']
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec']
$data['ru_stime.tv_usec'] / 1000000);
/* prints
User time: 1.088171
System time: 1.675315
*/
現在我們有相當多的系統時間佔用。這是因為腳本多次呼叫 microtime() 函數,該函數需要向作業系統發出請求,以取得所需時間。你也可能會注意到運行時間加起來不到 3 秒。這是因為有可能在伺服器上同時存在其他進程,而且腳本沒有 100% 使用 CPU 的整個 3 秒持續時間。
5、魔術常數
PHP 提供了取得目前行號(__LINE__)、檔案路徑(__FILE__)、目錄路徑(__DIR__)、函數名稱(__FUNCTION__)、類別名稱(__CLASS__)、方法名稱(__METHOD__) 和命名空間(__NAMESPACE__) 等有用的魔術常數。在這篇文章中不作一一介紹,但是我將告訴你一些用例。當包含其他腳本檔案時,使用 __FILE__ 常數(或使用 PHP5.3 新具有的 __DIR__ 常數):
// this is relative to the loaded script’s path
// it may cause problems when running scripts from different directories
require_once(‘config/database.php’);
// this is always relative to this file’s path
// no matter where it was included from
require_once(dirname(__FILE__) . ‘/config/database.php’);
使用 __LINE__ 讓除錯更為輕鬆。你可以追蹤到具體行號。
// some code
// …
my_debug(“some debug message”,__LINE__);
/* prints
Line 4: some debug message
*/
// some more code
// …
my_debug(“another debug message”, __LINE__);
/* prints
Line 11: another debug message
*/
function my_debug($msg, $line) {
echo “Line $line: $msgn”;
}
6、產生唯一識別碼
某些場景下,可能需要產生一個唯一的字串。我看到很多人使用 md5() 函數,即使它並不完全意味著這個目的:
// generate unique string
echo md5(time() . mt_rand(1,1000000));
There is actually a PHP function named uniqid() that ismeant to be used for this.
echo uniqid();
/* prints
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* prints
4bd67c9472340
*/
你可能會注意到,儘管字串是唯一的,前幾個字元卻是類似的,這是因為產生的字串與伺服器時間相關。但實際上也存在友好的一方面,由於每個新生成的 ID 會按字母順序排列,這樣排序就變得很簡單。為了減少重複的機率,你可以傳遞一個前綴,或第二個參數來增加熵:
// with prefix
echo uniqid(‘foo_’);
/* prints
foo_4bd67d6cd8b8f
*/
// with more entropy
echo uniqid(”,true);
/* prints
4bd67d6cd8b926.12135106
*/
// both
echo uniqid(‘bar_’,true);
/* prints
bar_4bd67da367b650.43684647
*/
這個函數會產生比 md5() 更短的字串,能節省一些空間。
7、序列化
你有沒有遇過需要在資料庫或文字檔案中儲存一個複雜變數的情況?你可能沒能想出一個格式化字串並轉換成陣列或物件的好方法,PHP 已經為你準備好此功能。有兩種序列化變數的流行方法。以下是一個例子,使用 serialize() 和 unserialize() 函數:
// a complex array
$myvar = array(
‘hello’,
42,
array(1,’two’),
‘apple’
);
// convert to a string
$string = serialize($myvar);
echo $string;
/* prints
a:4:{i:0;s:5:”hello”;i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3: ”two”;}i:3;s:5:”apple”;}
*/
// you can reproduce the original variable
$newvar = unserialize($string);
print_r($newvar);
/* prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/
這是原生的 PHP 序列化方法。然而,由於 JSON 近年來大受歡迎,PHP5.2 中已經加入了對 JSON 格式的支援。現在你可以使用 json_encode() 和 json_decode() 函數:
// a complex array
$myvar = array(
‘hello’,
42,
array(1,’two’),
‘apple’
);
// convert to a string
$string = json_encode($myvar);
echo $string;
/* prints
["hello",42,[1,"two"],”apple”]
*/
// you can reproduce the original variable
$newvar = json_decode($string);
print_r($newvar);
/* prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/
這將更為行之有效,尤其與 JavaScript 等許多其他語言相容。然而對於複雜的對象,某些資訊可能會遺失。
8、壓縮字串
在談到壓縮時,我們通常會想到檔案壓縮,如 ZIP 壓縮等。在 PHP 中字串壓縮也是可能的,但不涉及任何壓縮檔案。在下面的範例中,我們要利用 gzcompress() 和 gzuncompress() 函數:
$string =
“Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed m​​agna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. “;
$compressed = gzcompress($string);
echo “Original size: “. strlen($string).”n”;
/* prints
Original size: 800
*/
echo “Compressed size: “. strlen($compressed).”n”;
/* prints
Compressed size: 418
*/
// getting it back
$original = gzuncompress($compressed);
這種操作的壓縮率能達到 50% 左右。另外的函數 gzencode() 和 gzdecode() 能達到類似結果,透過使用不同的壓縮演算法。
9、註冊停止功能
有一個函數叫做register_shutdown_function(),可以讓你在某段腳本完成運行之前,執行一些指定代碼。假設你需要在腳本執行結束前捕獲一些基準統計信息,例如運行的時間長度:
// capture the start time
$start_time = microtime(true);
// do some stuff
// …
// display how long the script took
echo “execution took: “.
(microtime(true) – $start_time).
” seconds.”;
這似乎微不足道,你只需要在腳本運行的最後添加相關代碼。但是如果你呼叫過 exit() 函數,程式碼將無法運作。此外,如果有一個致命的錯誤,或者腳本被使用者意外終止,它可能無法再次運行。當你使用register_shutdown_function() 函數,程式碼會繼續執行,無論腳本是否停止執行:
$start_time = microtime(true);
register_shutdown_function('my_shutdown'); 🎜>// do some stuff
// …

function my_shutdown() {
global $start_time;

echo “execution took: “.
(microtime(true) – $start_time).
” seconds.”;
}

喜歡我的文章,請追蹤我的微信toceansoft

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1652
14
CakePHP 教程
1413
52
Laravel 教程
1304
25
PHP教程
1251
29
C# 教程
1224
24
在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

PHP 8.1中的枚舉(枚舉)是什麼? PHP 8.1中的枚舉(枚舉)是什麼? Apr 03, 2025 am 12:05 AM

PHP8.1中的枚舉功能通過定義命名常量增強了代碼的清晰度和類型安全性。 1)枚舉可以是整數、字符串或對象,提高了代碼可讀性和類型安全性。 2)枚舉基於類,支持面向對象特性,如遍歷和反射。 3)枚舉可用於比較和賦值,確保類型安全。 4)枚舉支持添加方法,實現複雜邏輯。 5)嚴格類型檢查和錯誤處理可避免常見錯誤。 6)枚舉減少魔法值,提升可維護性,但需注意性能優化。

描述紮實的原則及其如何應用於PHP的開發。 描述紮實的原則及其如何應用於PHP的開發。 Apr 03, 2025 am 12:04 AM

SOLID原則在PHP開發中的應用包括:1.單一職責原則(SRP):每個類只負責一個功能。 2.開閉原則(OCP):通過擴展而非修改實現變化。 3.里氏替換原則(LSP):子類可替換基類而不影響程序正確性。 4.接口隔離原則(ISP):使用細粒度接口避免依賴不使用的方法。 5.依賴倒置原則(DIP):高低層次模塊都依賴於抽象,通過依賴注入實現。

會話如何劫持工作,如何在PHP中減輕它? 會話如何劫持工作,如何在PHP中減輕它? Apr 06, 2025 am 12:02 AM

會話劫持可以通過以下步驟實現:1.獲取會話ID,2.使用會話ID,3.保持會話活躍。在PHP中防範會話劫持的方法包括:1.使用session_regenerate_id()函數重新生成會話ID,2.通過數據庫存儲會話數據,3.確保所有會話數據通過HTTPS傳輸。

解釋PHP中的晚期靜態綁定(靜態::)。 解釋PHP中的晚期靜態綁定(靜態::)。 Apr 03, 2025 am 12:04 AM

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

什麼是REST API設計原理? 什麼是REST API設計原理? Apr 04, 2025 am 12:01 AM

RESTAPI設計原則包括資源定義、URI設計、HTTP方法使用、狀態碼使用、版本控制和HATEOAS。 1.資源應使用名詞表示並保持層次結構。 2.HTTP方法應符合其語義,如GET用於獲取資源。 3.狀態碼應正確使用,如404表示資源不存在。 4.版本控制可通過URI或頭部實現。 5.HATEOAS通過響應中的鏈接引導客戶端操作。

您如何在PHP中有效處理異常(嘗試,捕捉,最後,投擲)? 您如何在PHP中有效處理異常(嘗試,捕捉,最後,投擲)? Apr 05, 2025 am 12:03 AM

在PHP中,異常處理通過try,catch,finally,和throw關鍵字實現。 1)try塊包圍可能拋出異常的代碼;2)catch塊處理異常;3)finally塊確保代碼始終執行;4)throw用於手動拋出異常。這些機制幫助提升代碼的健壯性和可維護性。

PHP中的匿名類是什麼?您何時可以使用它們? PHP中的匿名類是什麼?您何時可以使用它們? Apr 04, 2025 am 12:02 AM

匿名類在PHP中的主要作用是創建一次性使用的對象。 1.匿名類允許在代碼中直接定義沒有名字的類,適用於臨時需求。 2.它們可以繼承類或實現接口,增加靈活性。 3.使用時需注意性能和代碼可讀性,避免重複定義相同的匿名類。

See all articles