那些不曾了解的7个PHP函数和功能

一、任意参数数目的函数 创建可以接受任何参数数目的函数。使用func_get_args()函数:如下为引用的内容:      function foo(){          $args=func_get_args();          foreach($args as $k=>$v){              echo“arg”.($k+1).”:$v\n”;          }      }   二、使用Glob()查找文件 许多PHP函数具备长描述性的名称。然而可能会很难说出glob()函数能作的事情,除非你已经经过屡次使用并熟悉了它。能够把它看做是比scandir()函数更强大的版本,能够按照某种模式搜索文件。如下为引用的内容:      $files=glob('*.php');      print_r($files);      /*outputlookslike:      Array      (      [0]=>phptest.php      [1]=>pi.php      [2]=>post_output.php      [3]=>test.php      )      */ 三、内存使用信息 经过侦测脚本的内存使用状况,有利于代码的优化。PHP提供了一个垃圾收集器和一个很是复杂的内存管理器。脚本执行时所使用的内存量,有升有跌。为了获得当前的内存使用状况,咱们可使用memory_get_usage()函数。 若是须要得到任意时间点的最高内存使用量,则可使用memory_limit()函数。     如下为引用的内容:      echo“Initial:“.memory_get_usage().”bytes\n”;      /*prints      Initial:361400bytes      */      //let’suseupsomememory      for($i=0;$i<100000;$i++){      $array[]=md5($i);      }      //let'sremovehalfofthearray      for($i=0;$i<100000;$i++){      unset($array[$i]);      }      echo"Final:".memory_get_usage()."bytes\n";      /*prints      Final:885912bytes      */      echo"Peak:".memory_get_peak_usage()."bytes\n";      /*prints      Peak:13687072bytes      */ 四、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:blockoutputoperations      ru_inblock:blockinputoperations      ru_msgsnd:messagessent      ru_msgrcv:messagesreceived      ru_maxrss:maximumresidentsetsize      ru_ixrss:integralsharedmemorysize      ru_idrss:integralunshareddatasize      ru_minflt:pagereclaims      ru_majflt:pagefaults      ru_nsignals:signalsreceived      ru_nvcsw:voluntarycontextswitches      ru_nivcsw:involuntarycontextswitches      ru_nswap:swaps      ru_utime.tv_usec:usertimeused(microseconds)      ru_utime.tv_sec:usertimeused(seconds)      ru_stime.tv_usec:systemtimeused(microseconds)      ru_stime.tv_sec:systemtimeused(seconds) 要知道脚本消耗多少CPU功率,咱们须要看看‘usertime’和’systemtime’两个参数的值。秒和微秒部分默认是单独提供的。你能够除以100万微秒,并加上秒的参数值,获得一个十进制的总秒数。让咱们来看一个例子:如下为引用的内容:      //sleepfor3seconds(non-busy)      sleep(3);      $data=getrusage();      echo“Usertime:“.      ($data['ru_utime.tv_sec']+      $data['ru_utime.tv_usec']/1000000);      echo“Systemtime:“.      ($data['ru_stime.tv_sec']+      $data['ru_stime.tv_usec']/1000000);      /*prints      Usertime:0.011552      Systemtime:0      */ 尽管脚本运行用了大约3秒钟,CPU使用率却很是很是低。由于在睡眠运行的过程当中,该脚本实际上不消耗CPU资源。还有许多其余的任务,可能须要一段时间,但不占用相似等待磁盘操做等CPU时间。所以正如你所看到的,CPU 使用率和运行时间的实际长度并不老是相同的。下面是一个例子:     如下为引用的内容:      //loop10milliontimes(busy)      for($i=0;$i<10000000;$i++){           }      $data=getrusage();      echo"Usertime:".      ($data['ru_utime.tv_sec']+      $data['ru_utime.tv_usec']/1000000);      echo"Systemtime:".      ($data['ru_stime.tv_sec']+      $data['ru_stime.tv_usec']/1000000);      /*prints      Usertime:1.424592      Systemtime:0.004204      */ 这花了大约1.4秒的CPU时间,但几乎都是用户时间,由于没有系统调用。系统时间是指花费在执行程序的系统调用时的CPU开销。下面是一个例子:如下为引用的内容:      $start=microtime(true);      //keepcallingmicrotimeforabout3seconds      while(microtime(true)-$start<3){           }      $data=getrusage();      echo"Usertime:".      ($data['ru_utime.tv_sec']+      $data['ru_utime.tv_usec']/1000000);      echo"Systemtime:".      ($data['ru_stime.tv_sec']+      $data['ru_stime.tv_usec']/1000000);      /*prints      Usertime:1.088171      Systemtime:1.675315      */ 五、魔术常量 PHP提供了: 获取当前行号(__LINE__)、 文件路径(__FILE__)、 目录路径(__DIR__)、 函数名(__FUNCTION__)、 类名(__CLASS__)、 方法名(__METHOD__)、 命名空间(__NAMESPACE__) 等有用的魔术常量。当包含其余脚本文件时,使用__FILE__常量(或者使用PHP5.3新具备的__DIR__常量):     如下为引用的内容:      //thisisrelativetotheloadedscript'spath      //itmaycauseproblemswhenrunningscriptsfromdifferentdirectories      require_once('config/database.php');      //thisisalwaysrelativetothisfile'spath      //nomatterwhereitwasincludedfrom      require_once(dirname(__FILE__).'/config/database.php'); 使用__LINE__使得调试更为轻松。你能够跟踪到具体行号。     如下为引用的内容:      //somecode      //...      my_debug("somedebugmessage",__LINE__);      /*prints      Line4:somedebugmessage      */      //somemorecode      //...      my_debug("anotherdebugmessage",__LINE__);      /*prints      Line11:anotherdebugmessage      */      functionmy_debug($msg,$line){      echo"Line$line:$msg 六、生成惟一标识符 某些场景下,可能须要生成一个惟一的字符串。我看到不少人使用md5()函数,即便它并不彻底意味着这个目的:如下为引用的内容:      //generateuniquestring      echomd5(time().mt_rand(1,1000000));      ThereisactuallyaPHPfunctionnameduniqid()thatismeanttobeusedforthis.      //generateuniquestring      echouniqid();      /*prints      4bd67c947233e      */           //generateanotheruniquestring      echouniqid();      /*prints      4bd67c9472340      */ 你可能会注意到,尽管字符串是惟一的,前几个字符倒是相似的,这是由于生成的字符串与服务器时间相关。但实际上也存在友好的一方面,因为每一个新生成的ID会按字母顺序排列,这样排序就变得很简单。为了减小重复的几率,你能够传递一个前缀,或第二个参数来增长熵。如下为引用的内容:     //withprefix      echouniqid('foo_');      /*prints      foo_4bd67d6cd8b8f      */           //withmoreentropy      echouniqid('',true);      /*prints      4bd67d6cd8b926.12135106      */           //both      echouniqid('bar_',true);      /*prints      bar_4bd67da367b650.43684647      */ 这个函数将产生比md5()更短的字符串,能节省一些空间。 七、序列化 你有没有遇到过须要在数据库或文本文件存储一个复杂变量的状况?你可能没能想出一个格式化字符串并转换成数组或对象的好方法,PHP已经为你准备好此功能。有两种序列化变量的流行方法。下面是一个例子,使用serialize()和unserialize()函数。如下为引用的内容:     //acomplexarray      $myvar=array(      'hello',      42,      array(1,'two'),      'apple'      );           //converttoastring      $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";}      */      //youcanreproducetheoriginalvariable      $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()函数,如下为引用的内容:     //acomplexarray      $myvar=array(      ‘hello’,      42,      array(1,’two’),      ‘apple’      );      //converttoastring      $string=json_encode($myvar);           echo$string;      /*prints      ["hello",42,[1,"two"],”apple”]      */      //youcanreproducetheoriginalvariable      $newvar=json_decode($string);      print_r($newvar);      /*prints      Array      (      [0]=>hello      [1]=>42      [2]=>Array      (      [0]=>1      [1]=>two      )      [3]=>apple      )      */ 这将更为行之有效,尤为与JavaScript等许多其余语言兼容。然而对于复杂的对象,某些信息可能会丢失。
相关文章
相关标签/搜索