那些未曾了解的PHP函数和功能

开发 后端 前端
PHP真正的强大便是它的函数,文章将介绍一些实用的PHP函数和它的功能,这些函数并没有得到我们充分的利用,但它们的功能是非常强大的。

PHP的真正威力源自于它的函数,但有些PHP函数并没有得到充分的利用,也并不是所有人都会从头到尾一页一页地阅读手册和函数参考,这里将向您介绍这些实用的函数和功能。

51CTO推荐专题: PHP开发基础入门

1、任意参数数目的函数

你可能已经知道,PHP允许定义可选参数的函数。但也有完全允许任意数目的函数参数的方法。以下是可选参数的例子:

  1. 以下为引用的内容:  
  2.  
  3. //functionwith2optionalarguments  
  4. functionfoo($arg1=”,$arg2=”){  
  5.  
  6. echo“arg1:$arg1\n”;  
  7. echo“arg2:$arg2\n”;  
  8.  
  9. }  
  10.  
  11. foo(‘hello’,'world’);  
  12. /*prints:  
  13. arg1:hello  
  14. arg2:world  
  15. */  
  16.  
  17. foo();  
  18. /*prints:  
  19. arg1:  
  20. arg2:  
  21. */ 

现在让我们看看如何建立能够接受任何参数数目的函数。这一次需要使用func_get_args()函数:

  1. 以下为引用的内容:  
  2.  
  3. //yes,theargumentlistcanbeempty  
  4. functionfoo(){  
  5.  
  6. //returnsanarrayofallpassedarguments  
  7. $args=func_get_args();  
  8.  
  9. foreach($argsas$k=>$v){  
  10. echo“arg”.($k+1).”:$v\n”;  
  11. }  
  12.  
  13. }  
  14.  
  15. foo();  
  16. /*printsnothing*/  
  17.  
  18. foo(‘hello’);  
  19. /*prints  
  20. arg1:hello  
  21. */  
  22.  
  23. foo(‘hello’,‘world’,‘again’);  
  24. /*prints  
  25. arg1:hello  
  26. arg2:world  
  27. arg3:again  
  28. */ 

#p#

2、使用Glob()查找文件

许多PHP函数具有长描述性的名称。然而可能会很难说出glob()函数能做的事情,除非你已经通过多次使用并熟悉了它。可以把它看作是比scandir()函数更强大的版本,可以按照某种模式搜索文件。

  1. 以下为引用的内容:  
  2.  
  3. //getallphpfiles  
  4. $files=glob(‘*.php’);  
  5.  
  6. print_r($files);  
  7. /*outputlookslike:  
  8. Array  
  9. (  
  10. [0]=>phptest.php  
  11. [1]=>pi.php  
  12. [2]=>post_output.php  
  13. [3]=>test.php  
  14. )  
  15. */ 

你可以像这样获得多个文件:

  1. 以下为引用的内容:  
  2.  
  3. //getallphpfilesANDtxtfiles  
  4. $files=glob(‘*.{php,txt}’,GLOB_BRACE);  
  5.  
  6. print_r($files);  
  7. /*outputlookslike:  
  8. Array  
  9. (  
  10. [0]=>phptest.php  
  11. [1]=>pi.php  
  12. [2]=>post_output.php  
  13. [3]=>test.php  
  14. [4]=>log.txt  
  15. [5]=>test.txt  
  16. )  
  17. */ 

请注意,这些文件其实是可以返回一个路径,这取决于查询条件:

  1. 以下为引用的内容:  
  2.  
  3. $files=glob(‘../images/a*.jpg’);  
  4.  
  5. print_r($files);  
  6. /*outputlookslike:  
  7. Array  
  8. (  
  9. [0]=>../images/apple.jpg  
  10. [1]=>../images/art.jpg  
  11. )  
  12. */ 

如果你想获得每个文件的完整路径,你可以调用realpath()函数:

  1. 以下为引用的内容:  
  2.  
  3. $files=glob(‘../images/a*.jpg’);  
  4.  
  5. //appliesthefunctiontoeacharrayelement  
  6. $files=array_map(‘realpath’,$files);  
  7.  
  8. print_r($files);  
  9. /*outputlookslike:  
  10. Array  
  11. (  
  12. [0]=>C:\wamp\www\images\apple.jpg  
  13. [1]=>C:\wamp\www\images\art.jpg  
  14. )  
  15. */ 

 #p#

3、内存使用信息

通过侦测脚本的内存使用情况,有利于代码的优化。PHP提供了一个垃圾收集器和一个非常复杂的内存管理器。脚本执行时所使用的内存量,有升有跌。为了得到当前的内存使用情况,我们可以使用memory_get_usage()函数。如果需要获得任意时间点的***内存使用量,则可以使用memory_limit()函数。

  1. 以下为引用的内容:  
  2.  
  3. echo“Initial:“.memory_get_usage().”bytes\n”;  
  4. /*prints  
  5. Initial:361400bytes  
  6. */  
  7.  
  8. //let’suseupsomememory  
  9. for($i=0;$i<100000;$i++){  
  10. $array[]=md5($i);  
  11. }  
  12.  
  13. //let'sremovehalfofthearray  
  14. for($i=0;$i<100000;$i++){  
  15. unset($array[$i]);  
  16. }  
  17.  
  18. echo"Final:".memory_get_usage()."bytes\n";  
  19. /*prints  
  20. Final:885912bytes  
  21. */  
  22.  
  23. echo"Peak:".memory_get_peak_usage()."bytes\n";  
  24. /*prints  
  25. Peak:13687072bytes  
  26. */ 

4、CPU使用信息

为此,我们要利用getrusage()函数。请记住这个函数不适用于Windows平台。

  1. 以下为引用的内容:  
  2.  
  3. print_r(getrusage());  
  4. /*prints  
  5. Array  
  6. (  
  7. [ru_oublock]=>0  
  8. [ru_inblock]=>0  
  9. [ru_msgsnd]=>2  
  10. [ru_msgrcv]=>3  
  11. [ru_maxrss]=>12692  
  12. [ru_ixrss]=>764  
  13. [ru_idrss]=>3864  
  14. [ru_minflt]=>94  
  15. [ru_majflt]=>0  
  16. [ru_nsignals]=>1  
  17. [ru_nvcsw]=>67  
  18. [ru_nivcsw]=>4  
  19. [ru_nswap]=>0  
  20. [ru_utime.tv_usec]=>0  
  21. [ru_utime.tv_sec]=>0  
  22. [ru_stime.tv_usec]=>6269  
  23. [ru_stime.tv_sec]=>0  

这可能看起来有点神秘,除非你已经有系统管理员权限。以下是每个值的具体说明(你不需要记住这些):

  1. 以下为引用的内容:  
  2.  
  3. ru_oublock:blockoutputoperations  
  4. ru_inblock:blockinputoperations  
  5. ru_msgsnd:messagessent  
  6. ru_msgrcv:messagesreceived  
  7. ru_maxrss:maximumresidentsetsize  
  8. ru_ixrss:integralsharedmemorysize  
  9. ru_idrss:integralunshareddatasize  
  10. ru_minflt:pagereclaims  
  11. ru_majflt:pagefaults  
  12. ru_nsignals:signalsreceived  
  13. ru_nvcsw:voluntarycontextswitches  
  14. ru_nivcsw:involuntarycontextswitches  
  15. ru_nswap:swaps  
  16. ru_utime.tv_usec:usertimeused(microseconds)  
  17. ru_utime.tv_sec:usertimeused(seconds)  
  18. ru_stime.tv_usec:systemtimeused(microseconds)  
  19. ru_stime.tv_sec:systemtimeused(seconds) 

 

要知道脚本消耗多少CPU功率,我们需要看看‘usertime’和’systemtime’两个参数的值。秒和微秒部分默认是单独提供的。你可以除以100万微秒,并加上秒的参数值,得到一个十进制的总秒数。让我们来看一个例子:

  1. 以下为引用的内容:  
  2.  
  3. //sleepfor3seconds(non-busy)  
  4. sleep(3);  
  5.  
  6. $data=getrusage();  
  7. echo“Usertime:“.  
  8. ($data['ru_utime.tv_sec']+  
  9. $data['ru_utime.tv_usec']/1000000);  
  10. echo“Systemtime:“.  
  11. ($data['ru_stime.tv_sec']+  
  12. $data['ru_stime.tv_usec']/1000000);  
  13.  
  14. /*prints  
  15. Usertime:0.011552  
  16. Systemtime:0  
  17. */ 

尽管脚本运行用了大约3秒钟,CPU使用率却非常非常低。因为在睡眠运行的过程中,该脚本实际上不消耗CPU资源。还有许多其他的任务,可能需要一段时间,但不占用类似等待磁盘操作等CPU时间。因此正如你所看到的,CPU使用率和运行时间的实际长度并不总是相同的。下面是一个例子:

  1. 以下为引用的内容:  
  2.  
  3. //loop10milliontimes(busy)  
  4. for($i=0;$i<10000000;$i++){  
  5.  
  6. }  
  7.  
  8. $data=getrusage();  
  9. echo"Usertime:".  
  10. ($data['ru_utime.tv_sec']+  
  11. $data['ru_utime.tv_usec']/1000000);  
  12. echo"Systemtime:".  
  13. ($data['ru_stime.tv_sec']+  
  14. $data['ru_stime.tv_usec']/1000000);  
  15.  
  16. /*prints  
  17. Usertime:1.424592  
  18. Systemtime:0.004204  
  19. */ 

 

这花了大约1.4秒的CPU时间,但几乎都是用户时间,因为没有系统调用。系统时间是指花费在执行程序的系统调用时的CPU开销。下面是一个例子:

  1. 以下为引用的内容:  
  2.  
  3. $start=microtime(true);  
  4. //keepcallingmicrotimeforabout3seconds  
  5. while(microtime(true)-$start<3){  
  6.  
  7. }  
  8.  
  9. $data=getrusage();  
  10. echo"Usertime:".  
  11. ($data['ru_utime.tv_sec']+  
  12. $data['ru_utime.tv_usec']/1000000);  
  13. echo"Systemtime:".  
  14. ($data['ru_stime.tv_sec']+  
  15. $data['ru_stime.tv_usec']/1000000);  
  16.  
  17. /*prints  
  18. Usertime:1.088171  
  19. Systemtime:1.675315  
  20. */ 

现在我们有相当多的系统时间占用。这是因为脚本多次调用microtime()函数,该函数需要向操作系统发出请求,以获取所需时间。你也可能会注意到运行时间加起来不到3秒。这是因为有可能在服务器上同时存在其他进程,并且脚本没有100%使用CPU的整个3秒持续时间。

 #p#

5、魔术常量

PHP提供了获取当前行号(__LINE__)、文件路径(__FILE__)、目录路径(__DIR__)、函数名(__FUNCTION__)、类名(__CLASS__)、方法名(__METHOD__)和命名空间(__NAMESPACE__)等有用的魔术常量。在这篇文章中不作一一介绍,但是我将告诉你一些用例。当包含其他脚本文件时,使用__FILE__常量(或者使用PHP5.3新具有的__DIR__常量):

  1. 以下为引用的内容:  
  2.  
  3. //thisisrelativetotheloadedscript'spath  
  4. //itmaycauseproblemswhenrunningscriptsfromdifferentdirectories  
  5. require_once('config/database.php');  
  6.  
  7. //thisisalwaysrelativetothisfile'spath  
  8. //nomatterwhereitwasincludedfrom  
  9. require_once(dirname(__FILE__).'/config/database.php'); 

 

使用__LINE__使得调试更为轻松。你可以跟踪到具体行号。

  1. 以下为引用的内容:  
  2.  
  3. //somecode  
  4. //...  
  5. my_debug("somedebugmessage",__LINE__);  
  6. /*prints  
  7. Line4:somedebugmessage  
  8. */  
  9.  
  10. //somemorecode  
  11. //...  
  12. my_debug("anotherdebugmessage",__LINE__);  
  13. /*prints  
  14. Line11:anotherdebugmessage  
  15. */  
  16.  
  17. functionmy_debug($msg,$line){  
  18. echo"Line$line:$msg 

6、生成唯一标识符

某些场景下,可能需要生成一个唯一的字符串。我看到很多人使用md5()函数,即使它并不完全意味着这个目的:

  1. 以下为引用的内容:  
  2.  
  3. //generateuniquestring  
  4. echomd5(time().mt_rand(1,1000000));  
  5. ThereisactuallyaPHPfunctionnameduniqid()thatismeanttobeusedforthis.  
  6.  
  7. //generateuniquestring  
  8. echouniqid();  
  9. /*prints  
  10. 4bd67c947233e  
  11. */  
  12.  
  13. //generateanotheruniquestring  
  14. echouniqid();  
  15. /*prints  
  16. 4bd67c9472340  
  17. */ 

你可能会注意到,尽管字符串是唯一的,前几个字符却是类似的,这是因为生成的字符串与服务器时间相关。但实际上也存在友好的一方面,由于每个新生成的ID会按字母顺序排列,这样排序就变得很简单。为了减少重复的概率,你可以传递一个前缀,或第二个参数来增加熵。

  1. 以下为引用的内容:  
  2.  
  3. //withprefix  
  4. echouniqid('foo_');  
  5. /*prints  
  6. foo_4bd67d6cd8b8f  
  7. */  
  8.  
  9. //withmoreentropy  
  10. echouniqid('',true);  
  11. /*prints  
  12. 4bd67d6cd8b926.12135106  
  13. */  
  14.  
  15. //both  
  16. echouniqid('bar_',true);  
  17. /*prints  
  18. bar_4bd67da367b650.43684647  
  19. */ 

这个函数将产生比md5()更短的字符串,能节省一些空间。

7、序列化

你有没有遇到过需要在数据库或文本文件存储一个复杂变量的情况?你可能没能想出一个格式化字符串并转换成数组或对象的好方法,PHP已经为你准备好此功能。有两种序列化变量的流行方法。下面是一个例子,使用serialize()和unserialize()函数。以下为引用的内容:

  1. //acomplexarray  
  2. $myvar=array(  
  3. 'hello',  
  4. 42,  
  5. array(1,'two'),  
  6. 'apple'  
  7. );  
  8.  
  9. //converttoastring  
  10. $string=serialize($myvar);  
  11.  
  12. echo$string;  
  13. /*prints  
  14. 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";}  
  15. */  
  16.  
  17. //youcanreproducetheoriginalvariable  
  18. $newvar=unserialize($string);  
  19.  
  20. print_r($newvar);  
  21. /*prints  
  22. Array  
  23. (  
  24. [0]=>hello  
  25. [1]=>42  
  26. [2]=>Array  
  27. (  
  28. [0]=>1  
  29. [1]=>two  
  30. )  
  31.  
  32. [3]=>apple  
  33. )  
  34. */ 

这是原生的PHP序列化方法。然而,由于JSON近年来大受欢迎,PHP5.2中已经加入了对JSON格式的支持。现在你可以使用json_encode()和json_decode()函数,以下为引用的内容:

  1. //acomplexarray  
  2. $myvar=array(  
  3. ‘hello’,  
  4. 42,  
  5. array(1,’two’),  
  6. ‘apple’  
  7. );  
  8.  
  9. //converttoastring  
  10. $string=json_encode($myvar);  
  11.  
  12. echo$string;  
  13. /*prints  
  14. ["hello",42,[1,"two"],”apple”]  
  15. */  
  16.  
  17. //youcanreproducetheoriginalvariable  
  18. $newvar=json_decode($string);  
  19.  
  20. print_r($newvar);  
  21. /*prints  
  22. Array  
  23. (  
  24. [0]=>hello  
  25. [1]=>42  
  26. [2]=>Array  
  27. (  
  28. [0]=>1  
  29. [1]=>two  
  30. )  
  31.  
  32. [3]=>apple  
  33. )  
  34. */ 

这将更为行之有效,尤其与JavaScript等许多其他语言兼容。然而对于复杂的对象,某些信息可能会丢失。

文章转自PHP之家,

原文地址:http://www.phpzj.org/php_0002.html

【编辑推荐】

  1. PHP开发者不可不知的五件事
  2. PHP开发人员容易忽略的几点精华
  3. FirePHP:像Firebug那样调试你的PHP代码
  4. PHP应用JSON技巧讲解
  5. 解读PHP冒泡排序技巧

 

责任编辑:王晓东 来源: PHP之家
相关推荐

2013-10-21 17:57:54

2009-11-30 14:27:42

2009-11-25 14:06:53

PHP函数arsort

2009-12-01 15:14:32

PHP Substr库

2014-08-26 09:52:57

2009-12-03 15:23:48

PHP建立和关闭数据库

2023-06-27 17:02:05

PHP功能

2009-11-30 15:10:46

PHP substr函

2015-04-13 15:41:53

SAPF1

2009-11-26 13:50:11

PHP函数str_re

2009-11-25 17:48:18

PHP文件系统相关函数

2010-07-27 11:29:43

Flex

2009-12-04 09:50:59

PHP ob_star

2009-11-30 17:49:51

PHP函数preg_s

2019-07-02 11:01:35

SpringBean配置

2010-09-02 15:45:18

PHP函数echo

2015-03-20 13:20:11

PHP框架全方面了解PHP

2009-12-03 15:40:41

PHP获取数据库表信息

2009-11-26 14:38:08

PHP函数echo()

2009-11-26 13:52:07

PHP字符串替换函数s
点赞
收藏

51CTO技术栈公众号