九個很有用的PHP代碼
下面是九個PHP中很有用的功能,不知道你用過了嗎?
1. 函數的任意數目的參數你可能知道PHP允許你定義一個默認參數的函數。但你可能并不知道PHP還允許你定義一個完全任意的參數的函數
下面是一個示例向你展示了默認參數的函數:
// 兩個默認參數的函數function foo($arg1 = ’’, $arg2 = ’’) {echo "arg1: $arg1n";echo "arg2: $arg2n";}foo(’hello’,’world’);/* 輸出:arg1: helloarg2: world*/foo();/* 輸出:arg1:arg2:*/
現在我們來看一看一個不定參數的函數,其使用到了?func_get_args()方法:
// 是的,形參列表為空function foo() {// 取得所有的傳入參數的數組$args = func_get_args();foreach ($args as $k => $v) {echo "arg".($k+1).": $vn";}}foo();/* 什么也不會輸出 */foo(’hello’);/* 輸出arg1: hello*/foo(’hello’, ’world’, ’again’);/* 輸出arg1: helloarg2: worldarg3: again*/2. 使用 Glob() 查找文件
很多PHP的函數都有一個比較長的自解釋的函數名,但是,當你看到?glob() 的時候,你可能并不知道這個函數是用來干什么的,除非你對它已經很熟悉了。
你可以認為這個函數就好?scandir() 一樣,其可以用來查找文件。
// 取得所有的后綴為PHP的文件$files = glob(’*.php’);print_r($files);/* 輸出:Array( [0] => phptest.php [1] => pi.php [2] => post_output.php [3] => test.php)*/
你還可以查找多種后綴名
// 取PHP文件和TXT文件$files = glob(’*.{php,txt}’, GLOB_BRACE);print_r($files);/* 輸出: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);/* 輸出: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_get_peak_usage() 函數。
echo "Initial: ".memory_get_usage()." bytes n";/* 輸出Initial: 361400 bytes*/// 使用內存for ($i = 0; $i < 100000; $i++) {$array []= md5($i);}// 刪除一半的內存for ($i = 0; $i < 100000; $i++) {unset($array[$i]);}echo "Final: ".memory_get_usage()." bytes n";/* printsFinal: 885912 bytes*/echo "Peak: ".memory_get_peak_usage()." bytes n";/* 輸出峰值Peak: 13687072 bytes*/4. CPU使用信息
使用?getrusage() 函數可以讓你知道CPU的使用情況。注意,這個功能在Windows下不可用。
print_r(getrusage());/* 輸出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)*/
這個結構看上出很晦澀,除非你對CPU很了解。下面一些解釋:
ru_oublock: 塊輸出操作ru_inblock: 塊輸入操作ru_msgsnd: 發送的messageru_msgrcv: 收到的messageru_maxrss: 最大駐留集大小ru_ixrss: 全部共享內存大小ru_idrss:全部非共享內存大小ru_minflt: 頁回收ru_majflt: 頁失效ru_nsignals: 收到的信號ru_nvcsw: 主動上下文切換ru_nivcsw: 被動上下文切換ru_nswap: 交換區ru_utime.tv_usec: 用戶態時間 (microseconds)ru_utime.tv_sec: 用戶態時間(seconds)ru_stime.tv_usec: 系統內核時間 (microseconds)ru_stime.tv_sec: 系統內核時間?(seconds)要看到你的腳本消耗了多少CPU,我們需要看看“用戶態的時間”和“系統內核時間”的值。秒和微秒部分是分別提供的,您可以把微秒值除以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);/* 輸出User time: 0.011552System time: 0*/
sleep是不占用系統時間的,我們可以來看下面的一個例子:
// loop 10 million times (busy)for($i=0;$i<10000000;$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);/* 輸出User time: 1.424592System time: 0.004204*/
這花了大約14秒的CPU時間,幾乎所有的都是用戶的時間,因為沒有系統調用。
系統時間是CPU花費在系統調用上的上執行內核指令的時間。下面是一個例子:
$start = microtime(true);// keep calling microtime for about 3 secondswhile(microtime(true) - $start < 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);/* printsUser time: 1.088171System time: 1.675315*/
我們可以看到上面這個例子更耗CPU。
5. 系統常量PHP 提供非常有用的系統常量 可以讓你得到當前的行號 (__LINE__),文件 (__FILE__),目錄 (__DIR__),函數名 (__FUNCTION__),類名(__CLASS__),方法名(__METHOD__) 和名字空間 (__NAMESPACE__),很像C語言。
我們可以以為這些東西主要是用于調試,當也不一定,比如我們可以在include其它文件的時候使用?__FILE__ (當然,你也可以在 PHP 5.3以后使用 __DIR__ ),下面是一個例子。
// this is relative to the loaded script’s path// it may cause problems when running scripts from different directoriesrequire_once(’config/database.php’);// this is always relative to this file’s path// no matter where it was included fromrequire_once(dirname(__FILE__) . ’/config/database.php’);
下面是使用 __LINE__ 來輸出一些debug的信息,這樣有助于你調試程序:
// some code// ...my_debug("some debug message", __LINE__);/* 輸出Line 4: some debug message*/// some more code// ...my_debug("another debug message", __LINE__);/* 輸出Line 11: another debug message*/function my_debug($msg, $line) {echo "Line $line: $msgn";}6.生成唯一的ID
有很多人使用 md5() 來生成一個唯一的ID,如下所示:
// generate unique stringecho md5(time() . mt_rand(1,1000000));
其實,PHP中有一個叫?uniqid() 的函數是專門用來干這個的:
// generate unique stringecho uniqid();/* 輸出4bd67c947233e*/// generate another unique stringecho uniqid();/* 輸出4bd67c9472340*/
可能你會注意到生成出來的ID前幾位是一樣的,這是因為生成器依賴于系統的時間,這其實是一個非常不錯的功能,因為你是很容易為你的這些ID排序的。這點MD5是做不到的。
你還可以加上前綴避免重名:
// 前綴echo uniqid(’foo_’);/* 輸出foo_4bd67d6cd8b8f*/// 有更多的熵echo uniqid(’’,true);/* 輸出4bd67d6cd8b926.12135106*/// 都有echo uniqid(’bar_’,true);/* 輸出bar_4bd67da367b650.43684647*/
而且,生成出來的ID會比MD5生成的要短,這會讓你節省很多空間。
7. 序列化你是否會把一個比較復雜的數據結構存到數據庫或是文件中?你并不需要自己去寫自己的算法。PHP早已為你做好了,其提供了兩個函數:?serialize() 和 unserialize():
// 一個復雜的數組$myvar = array(’hello’,42,array(1,’two’),’apple’);// 序列化$string = serialize($myvar);echo $string;/* 輸出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";}*/// 反序例化$newvar = unserialize($string);print_r($newvar);/* 輸出Array( [0] => hello [1] => 42 [2] => Array( [0] => 1 [1] => two) [3] => apple)*/
這是PHP的原生函數,然而在今天JSON越來越流行,所以在PHP5.2以后,PHP開始支持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);/* printsArray( [0] => hello [1] => 42 [2] => Array( [0] => 1 [1] => two) [3] => apple)*/
這看起來更為緊湊一些了,而且還兼容于Javascript和其它語言。但是對于一些非常復雜的數據結構,可能會造成數據丟失。
8. 字符串壓縮當我們說到壓縮,我們可能會想到文件壓縮,其實,字符串也是可以壓縮的。PHP提供了?gzcompress() 和 gzuncompress() 函數:
$string ="Lorem ipsum dolor sit amet, consecteturadipiscing elit. Nunc ut elit id mi ultriciesadipiscing. Nulla facilisi. Praesent pulvinar,sapien vel feugiat vestibulum, nulla dui pretium orci,non ultricies elit lacus quis ante. Lorem ipsum dolorsit amet, consectetur adipiscing elit. Aliquampretium ullamcorper urna quis iaculis. Etiam ac massased turpis tempor luctus. Curabitur sed nibh eu elitmollis congue. Praesent ipsum diam, consectetur vitaeornare a, aliquam a nunc. In id magna pellentesquetellus posuere adipiscing. Sed non mi metus, at laciniaaugue. Sed magna nisi, ornare in mollis in, mollissed nunc. Etiam at justo in leo congue mollis.Nullam in neque eget metus hendrerit scelerisqueeu non enim. Ut malesuada lacus eu nulla bibendumid euismod urna sodales. ";$compressed = gzcompress($string);echo "Original size: ". strlen($string)."n";/* 輸出原始大小Original size: 800*/echo "Compressed size: ". strlen($compressed)."n";/* 輸出壓縮后的大小Compressed size: 418*/// 解壓縮$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 tookecho "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.";}
文章:來源
相關文章:
