8 個必備的PHP功能開發_PHP教程

來源:互聯網
上載者:User
做過PHP開發的程式員應該清楚,PHP中有很多內建的功能,掌握了它們,可以協助你在做PHP開發時更加得心應手,本文將分享8個開發必備的PHP功能,個個都非常實用,希望各位PHP開發人員能夠掌握。

1、傳遞任意數量的函數參數 我們在.NET或者JAVA編程中,一般函數參數個數都是固定的,但是PHP允許你使用任意個數的參數。下面這個樣本向你展示了PHP函數的預設參數: Php代碼
  1. // 兩個預設參數的函數
  2. function foo($arg1 = ”, $arg2 = ”) {
  3. echo “arg1: $arg1\n”;
  4. echo “arg2: $arg2\n”;
  5. }
  6. foo(‘hello’,'world’);
  7. /* 輸出:
  8. arg1: hello
  9. arg2: world
  10. */
  11. foo();
  12. /* 輸出:
  13. arg1:
  14. arg2:
  15. */
  16. 下面這個樣本是PHP的不定參數用法,其使用到了 [url=http://us2.php.net/manual/en/function.func-get-args.php]func_get_args()[/url]方法:
  17. // 是的,形參列表為空白
  18. function foo() {
  19. // 取得所有的傳入參數的數組
  20. $args = func_get_args();
  21. foreach ($args as $k => $v) {
  22. echo “arg”.($k+1).”: $v\n”;
  23. }
  24. }
  25. foo();
  26. /* 什麼也不會輸出 */
  27. foo(‘hello’);
  28. /* 輸出
  29. arg1: hello
  30. */
  31. foo(‘hello’, ‘world’, ‘again’);
  32. /* 輸出
  33. arg1: hello
  34. arg2: world
  35. arg3: again
  36. */
2、使用glob()尋找檔案 大部分PHP函數的函數名從字面上都可以理解其用途,但是當你看到 glob() 的時候,你也許並不知道這是用來做什麼的,其實glob()和scandir() 一樣,可以用來尋找檔案,請看下面的用法: Php代碼
  1. // 取得所有的尾碼為PHP的檔案
  2. $files = glob(‘*.php’);
  3. print_r($files);
  4. /* 輸出:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. )
  12. */
你還可以尋找多種尾碼名: Php代碼
  1. // 取PHP檔案和TXT檔案
  2. $files = glob(‘*.{php,txt}’, GLOB_BRACE);
  3. print_r($files);
  4. /* 輸出:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. [4] => log.txt
  12. [5] => test.txt
  13. )
  14. */
你還可以加上路徑: Php代碼
  1. $files = glob(‘../images/a*.jpg’);
  2. print_r($files);
  3. /* 輸出:
  4. Array
  5. (
  6. [0] => ../images/apple.jpg
  7. [1] => ../images/art.jpg
  8. )
  9. */
如果你想得到絕對路徑,你可以調用 realpath() 函數: Php代碼
  1. $files = glob(‘../images/a*.jpg’);
  2. // applies the function to each array element
  3. $files = array_map(‘realpath’,$files);
  4. print_r($files);
  5. /* output looks like:
  6. Array
  7. (
  8. [0] => C:\wamp\www\images\apple.jpg
  9. [1] => C:\wamp\www\images\art.jpg
  10. )
  11. */
3、擷取記憶體使用量情況資訊 PHP的記憶體回收機制已經非常強大,你也可以使用PHP指令碼擷取當前記憶體的使用方式,調用memory_get_usage() 函數擷取當期記憶體使用量情況,調用memory_get_peak_usage() 函數擷取記憶體使用量的峰值。參考代碼如下: Php代碼
  1. echo “Initial: “.memory_get_usage().” bytes \n”;
  2. /* 輸出
  3. Initial: 361400 bytes
  4. */
  5. // 使用記憶體
  6. for ($i = 0; $i < 100000; $i++) {
  7. $array []= md5($i);
  8. }
  9. // 刪除一半的記憶體
  10. for ($i = 0; $i < 100000; $i++) {
  11. unset($array[$i]);
  12. }
  13. echo “Final: “.memory_get_usage().” bytes \n”;
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo “Peak: “.memory_get_peak_usage().” bytes \n”;
  18. /* 輸出峰值
  19. Peak: 13687072 bytes
  20. */
4、擷取CPU使用方式資訊 擷取了記憶體使用量情況,也可以使用PHP的 getrusage()擷取CPU使用方式,該方法在windows下不可用。 Php代碼
  1. print_r(getrusage());
  2. /* 輸出
  3. Array
  4. (
  5. [ru_oublock] => 0
  6. [ru_inblock] => 0
  7. [ru_msgsnd] => 2
  8. [ru_msgrcv] => 3
  9. [ru_maxrss] => 12692
  10. [ru_ixrss] => 764
  11. [ru_idrss] => 3864
  12. [ru_minflt] => 94
  13. [ru_majflt] => 0
  14. [ru_nsignals] => 1
  15. [ru_nvcsw] => 67
  16. [ru_nivcsw] => 4
  17. [ru_nswap] => 0
  18. [ru_utime.tv_usec] => 0
  19. [ru_utime.tv_sec] => 0
  20. [ru_stime.tv_usec] => 6269
  21. [ru_stime.tv_sec] => 0
  22. )
  23. */
這個結構看上出很晦澀,除非你對CPU很瞭解。下面一些解釋:
  • ru_oublock: 塊輸出操作
  • ru_inblock: 塊輸入操作
  • ru_msgsnd: 發送的message
  • ru_msgrcv: 收到的message
  • ru_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萬,並把它添加到秒的值後,可以得到有小數部分的秒數。 Php代碼
  1. // sleep for 3 seconds (non-busy)
  2. sleep(3);
  3. $data = getrusage();
  4. echo “User time: “.
  5. ($data['ru_utime.tv_sec'] +
  6. $data['ru_utime.tv_usec'] / 1000000);
  7. echo “System time: “.
  8. ($data['ru_stime.tv_sec'] +
  9. $data['ru_stime.tv_usec'] / 1000000);
  10. /* 輸出
  11. User time: 0.011552
  12. System time: 0
  13. */
sleep是不佔用系統時間的,我們可以來看下面的一個例子: Php代碼
  1. // loop 10 million times (busy)
  2. for($i=0;$i<10000000;$i++) {
  3. }
  4. $data = getrusage();
  5. echo “User time: “.
  6. ($data['ru_utime.tv_sec'] +
  7. $data['ru_utime.tv_usec'] / 1000000);
  8. echo “System time: “.
  9. ($data['ru_stime.tv_sec'] +
  10. $data['ru_stime.tv_usec'] / 1000000);
  11. /* 輸出
  12. User time: 1.424592
  13. System time: 0.004204
  14. */
這花了大約14秒的CPU時間,幾乎所有的都是使用者的時間,因為沒有系統調用。 系統時間是CPU花費在系統調用上的上執行核心指令的時間。下面是一個例子: Php代碼
  1. $start = microtime(true);
  2. // keep calling microtime for about 3 seconds
  3. while(microtime(true) – $start < 3) {
  4. }
  5. $data = getrusage();
  6. echo “User time: “.
  7. ($data['ru_utime.tv_sec'] +
  8. $data['ru_utime.tv_usec'] / 1000000);
  9. echo “System time: “.
  10. ($data['ru_stime.tv_sec'] +
  11. $data['ru_stime.tv_usec'] / 1000000);
  12. /* prints
  13. User time: 1.088171
  14. System time: 1.675315
  15. */
我們可以看到上面這個例子更耗CPU。 5、擷取系統常量 PHP 提供非常有用的系統常量 可以讓你得到當前的行號 (__LINE__),檔案 (__FILE__),目錄 (__DIR__),函數名 (__FUNCTION__),類名(__CLASS__),方法名(__METHOD__) 和名字空間 (__NAMESPACE__),很像C語言。 我們可以以為這些東西主要是用於調試,當也不一定,比如我們可以在include其它檔案的時候使用?__FILE__ (當然,你也可以在 PHP 5.3以後使用 __DIR__ ),下面是一個例子。 Php代碼
  1. // this is relative to the loaded script’s path
  2. // it may cause problems when running scripts from different directories
  3. require_once(‘config/database.php’);
  4. // this is always relative to this file’s path
  5. // no matter where it was included from
  6. require_once(dirname(__FILE__) . ‘/config/database.php’);
下面是使用 __LINE__ 來輸出一些debug的資訊,這樣有助於你偵錯工具: Php代碼
  1. // some code
  2. // …
  3. my_debug(“some debug message”, __LINE__);
  4. /* 輸出
  5. Line 4: some debug message
  6. */
  7. // some more code
  8. // …
  9. my_debug(“another debug message”, __LINE__);
  10. /* 輸出
  11. Line 11: another debug message
  12. */
  13. function my_debug($msg, $line) {
  14. echo “Line $line: $msg\n”;
  15. }
6、產生唯一的id 很多朋友都利用md5()來產生唯一的編號,但是md5()有幾個缺點:1、無序,導致資料庫中排序效能下降。2、太長,需要更多的儲存空間。其實PHP中內建一個函數來產生唯一的id,這個函數就是uniqid()。下面是用法: Php代碼
  1. // generate unique string
  2. echo uniqid();
  3. /* 輸出
  4. 4bd67c947233e
  5. */
  6. // generate another unique string
  7. echo uniqid();
  8. /* 輸出
  9. 4bd67c9472340
  10. */
該演算法是根據CPU時間戳記來產生的,所以在相近的時間段內,id前幾位是一樣的,這也方便id的排序,如果你想更好的避免重複,可以在id前加上首碼,如: Php代碼
  1. // 首碼
  2. echo uniqid(‘foo_’);
  3. /* 輸出
  4. foo_4bd67d6cd8b8f
  5. */
  6. // 有更多的熵
  7. echo uniqid(”,true);
  8. /* 輸出
  9. 4bd67d6cd8b926.12135106
  10. */
  11. // 都有
  12. echo uniqid(‘bar_’,true);
  13. /* 輸出
  14. bar_4bd67da367b650.43684647
  15. */
7、序列化 PHP序列化功能大家可能用的比較多,也比較常見,當你需要把資料存到資料庫或者檔案中是,你可以利用PHP中的serialize() 和 unserialize()方法來實現序列化和還原序列化,代碼如下: Php代碼
  1. // 一個複雜的數組
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // 序列化
  9. $string = serialize($myvar);
  10. echo $string;
  11. /* 輸出
  12. 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”;}
  13. */
  14. // 反序例化
  15. $newvar = unserialize($string);
  16. print_r($newvar);
  17. /* 輸出
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
如何序列化成json格式呢,放心,php也已經為你做好了,使用php 5.2以上版本的使用者可以使用json_encode() 和 json_decode() 函數來實現json格式的序列化,代碼如下: Php代碼
  1. // a complex array
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // convert to a string
  9. $string = json_encode($myvar);
  10. echo $string;
  11. /* prints
  12. ["hello",42,[1,"two"],”apple”]
  13. */
  14. // you can reproduce the original variable
  15. $newvar = json_decode($string);
  16. print_r($newvar);
  17. /* prints
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
8、字串壓縮 當我們說到壓縮,我們可能會想到檔案壓縮,其實,字串也是可以壓縮的。PHP提供了 gzcompress() 和gzuncompress() 函數: Php代碼
  1. $string =
  2. “Lorem ipsum dolor sit amet, consectetur
  3. adipiscing elit. Nunc ut elit id mi ultricies
  4. adipiscing. Nulla facilisi. Praesent pulvinar,
  5. sapien vel feugiat vestibulum, nulla dui pretium orci,
  6. non ultricies elit lacus quis ante. Lorem ipsum dolor
  7. sit amet, consectetur adipiscing elit. Aliquam
  8. pretium ullamcorper urna quis iaculis. Etiam ac massa
  9. sed turpis tempor luctus. Curabitur sed nibh eu elit
  10. mollis congue. Praesent ipsum diam, consectetur vitae
  11. ornare a, aliquam a nunc. In id magna pellentesque
  12. tellus posuere adipiscing. Sed non mi metus, at lacinia
  13. augue. Sed magna nisi, ornare in mollis in, mollis
  14. sed nunc. Etiam at justo in leo congue mollis.
  15. Nullam in neque eget metus hendrerit scelerisque
  16. eu non enim. Ut malesuada lacus eu nulla bibendum
  17. id euismod urna sodales. “;
  18. $compressed = gzcompress($string);
  19. echo “Original size: “. strlen($string).”\n”;
  20. /* 輸出原始大小
  21. Original size: 800
  22. */
  23. echo “Compressed size: “. strlen($compressed).”\n”;
  24. /* 輸出壓縮後的大小
  25. Compressed size: 418
  26. */
  27. // 解壓縮
  28. $original = gzuncompress($compressed);
幾乎有50% 壓縮比率。同時,你還可以使用 gzencode() 和 gzdecode() 函數來壓縮,只不用其用了不同的壓縮演算法。 以上就是8個開發必備的PHP功能,是不是都很實用呢?


原文出處:8個開發必備的PHP功能

http://www.bkjia.com/PHPjc/735057.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/735057.htmlTechArticle做過PHP開發的程式員應該清楚,PHP中有很多內建的功能,掌握了它們,可以協助你在做PHP開發時更加得心應手,本文將分享8個開發必備的...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.