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

本文出拓勝科技,請追蹤我的微信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
PHP行動:現實世界中的示例和應用程序PHP行動:現實世界中的示例和應用程序Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:輕鬆創建交互式Web內容PHP:輕鬆創建交互式Web內容Apr 14, 2025 am 12:15 AM

PHP可以輕鬆創建互動網頁內容。 1)通過嵌入HTML動態生成內容,根據用戶輸入或數據庫數據實時展示。 2)處理表單提交並生成動態輸出,確保使用htmlspecialchars防XSS。 3)結合MySQL創建用戶註冊系統,使用password_hash和預處理語句增強安全性。掌握這些技巧將提升Web開發效率。

PHP和Python:比較兩種流行的編程語言PHP和Python:比較兩種流行的編程語言Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP的持久相關性:它還活著嗎?PHP的持久相關性:它還活著嗎?Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP的當前狀態:查看網絡開發趨勢PHP的當前狀態:查看網絡開發趨勢Apr 13, 2025 am 12:20 AM

PHP在現代Web開發中仍然重要,尤其在內容管理和電子商務平台。 1)PHP擁有豐富的生態系統和強大框架支持,如Laravel和Symfony。 2)性能優化可通過OPcache和Nginx實現。 3)PHP8.0引入JIT編譯器,提升性能。 4)雲原生應用通過Docker和Kubernetes部署,提高靈活性和可擴展性。

PHP與其他語言:比較PHP與其他語言:比較Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP與Python:核心功能PHP與Python:核心功能Apr 13, 2025 am 12:16 AM

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP:網絡開發的關鍵語言PHP:網絡開發的關鍵語言Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。