PHP程式設計師要知道的幾個有用的PHP函式
1. 記憶體使用情況 memory_get_usage()
注意程式的記憶體使用情況,能讓PHP程式設計師更好的優化自己的PHP程式。
PHP有自己的垃圾回收機制,同時也有很複雜的記憶體管理機制。PHP程式設計師可以通過memory_get_usage()函式看觀察自己的PHP程式的記憶體使用情況,示例程式碼如下:echo '開始:' . memory_get_usage() . 'bytes \n';
$str = str_repeat('Hello world', 1234);
echo memory_get_usage() . 'bytes \n';
unset($str);
echo memory_get_usage() . 'bytes \n';
echo '記憶體使用峰值為:' . memory_get_peak_usage() . 'bytes \n';
注:若用 memory_get_usage(true) 則是顯示不包括此函式所佔的記憶體,和linux中
ll | grep str | grep -v grep 的-v類似
相關的函式還有 getrusage() 用於得到 cpu的使用情況
php.net 中的示例程式碼如下:$dat = getrusage();
echo $dat["ru_nswap"]; // number of swaps
echo $dat["ru_majflt"]; // number of page faults
echo $dat["ru_utime.tv_sec"]; // user time used (seconds)
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)
2. PHP還提供了很多好用的系統常量
如:__LINE__(當前行號),__FILE__(檔案路徑),__DIR__(目錄)
__FUNCTION__(函式名),__CLASS__(類名)
這些函式主要是用來除錯的,不過也有其他的用法
如:dirname(__FILE__) 在include時,可得到當前的檔案路徑
__DIR__在PHP5.3後才有
3. 用 uniqid() 來生成唯一的ID
在實際的應用中這個函式很給力的
4. 字串壓縮 gzcompress()
我們會經常聽說對檔案進行壓縮,還有用 gzip 對來優化網站
PHP為程式設計師提供了對字串的壓縮,不知你用過嗎?
注:對應的解壓函式為 gzuncompress(), 壓縮比率可以達到 50%
5. 註冊停止前執行函式 register_shutdown_time()
這個函式,讓你在整個指令碼停時前執行程式碼,最常用的就是獲取程式的執行時間
當然還有其他的用法,下面是php.net給出的一段程式碼:function shutdown_function (&$test) {
echo __FUNCTION__.'(): $test = '.$test."\n";
}
$test = 1;
register_shutdown_function('shutdown_function', &$test);
echo '$test = '.$test."\n";
// do some stuff and change the variable values
$test = 2;
// now the shutdown function gets called
exit(0);
6. 用 glob() 來查詢檔案foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}