1. 函数的任意数目的参数

你可能知道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:

现在我们来看一看一个不定参数的函数,其使用到了?func_get_args()方法:

  1. // 是的,形参列表为空
  2. function foo() {
  3. // 取得所有的传入参数的数组
  4. $args = func_get_args();
  5. foreach ($args as $k => $v) {
  6. echo "arg".($k+1).": $v\n";
  7. }
  8. }
  9. foo();
  10. /* 什么也不会输出 */
  11. foo('hello');
  12. /* 输出
  13. arg1: hello
  14. */
  15. foo('hello', 'world', 'again');
  16. /* 输出
  17. arg1: hello
  18. arg2: world
  19. arg3: again
  20. */

2. 使用 Glob() 查找文件

很多PHP的函数都有一个比较长的自解释的函数名,但是,当你看到?glob() 的时候,你可能并不知道这个函数是用来干什么的,除非你对它已经很熟悉了。

你可以认为这个函数就好?scandir() 一样,其可以用来查找文件。

  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. */

你还可以查找多种后缀名

  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. */

你还可以加上路径:

  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() 函数:

  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 是有垃圾回收机制的,而且有一套很复杂的内存管理机制。你可以知道你的脚本所使用的内存情况。要知道当前内存使用情况,你可以使用? memory_get_usage() 函数,如果你想知道使用内存的峰值,你可以调用memory_get_peak_usage() 函数。

  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使用信息

使用?getrusage() 函数可以让你知道CPU的使用情况。注意,这个功能在Windows下不可用。

  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万,并把它添加到秒的值后,可以得到有小数部分的秒数。

  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是不占用系统时间的,我们可以来看下面的一个例子:

  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花费在系统调用上的上执行内核指令的时间。下面是一个例子:

  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__ ),下面是一个例子。

  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的信息,这样有助于你调试程序:

  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() 来生成一个唯一的ID,如下所示:

  1. // generate unique string
  2. echo md5(time() . mt_rand(1,1000000));

其实,PHP中有一个叫?uniqid() 的函数是专门用来干这个的:

  1. // generate unique string
  2. echo uniqid();
  3. /* 输出
  4. 4bd67c947233e
  5. */
  6. // generate another unique string
  7. echo uniqid();
  8. /* 输出
  9. 4bd67c9472340
  10. */

可能你会注意到生成出来的ID前几位是一样的,这是因为生成器依赖于系统的时间,这其实是一个非常不错的功能,因为你是很容易为你的这些ID排序的。这点MD5是做不到的。

你还可以加上前缀避免重名:

  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. */

而且,生成出来的ID会比MD5生成的要短,这会让你节省很多空间。

7. 序列化

你是否会把一个比较复杂的数据结构存到数据库或是文件中?你并不需要自己去写自己的算法。PHP早已为你做好了,其提供了两个函数:?serialize() 和 unserialize():

  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. */

这是PHP的原生函数,然而在今天JSON越来越流行,所以在PHP5.2以后,PHP开始支持JSON,你可以使用 json_encode() 和 json_decode() 函数

  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. */

这看起来更为紧凑一些了,而且还兼容于Javascript和其它语言。但是对于一些非常复杂的数据结构,可能会造成数据丢失。

8. 字符串压缩

当我们说到压缩,我们可能会想到文件压缩,其实,字符串也是可以压缩的。PHP提供了?gzcompress() 和 gzuncompress() 函数:

  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() 函数来压缩,只不用其用了不同的压缩算法。

9. 注册停止函数

有一个函数叫做?register_shutdown_function(),可以让你在整个脚本停时前运行代码。让我们看下面的一个示例:

  1. // capture the start time
  2. $start_time = microtime(true);
  3. // do some stuff
  4. // ...
  5. // display how long the script took
  6. echo "execution took: ".
  7. (microtime(true) - $start_time).
  8. " seconds.";

上面这个示例只不过是用来计算某个函数运行的时间。然后,如果你在函数中间调用?exit() 函数,那么你的最后的代码将不会被运行到。并且,如果该脚本在浏览器终止(用户按停止按钮),其也无法被运行。

而当我们使用了register_shutdown_function()后,你的程序就算是在脚本被停止后也会被运行:

  1. $start_time = microtime(true);
  2. register_shutdown_function('my_shutdown');
  3. // do some stuff
  4. // ...
  5. function my_shutdown() {
  6. global $start_time;
  7. echo "execution took: ".
  8. (microtime(true) - $start_time).
  9. " seconds.";
  10. }

原文链接:http://coolshell.cn/articles/2394.html

【编辑推荐】

九个PHP很有用的功能的更多相关文章

  1. ipython, 一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数

    一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数. 若用的是fish s ...

  2. php九个很有用的功能

    1.任意数目的参数 // 两个默认参数的函数 function foo($arg1 = '', $arg2 = '') { echo "arg1: $arg1\n"; echo & ...

  3. [转]redis-cli的一些有趣也很有用的功能

    本文转至:http://www.tuicool.com/articles/Yvqm2ev http://mdba.cn/category/redis/ redis-cli我们最常用的两个参数就是-h. ...

  4. redis-cli的一些有趣也很有用的功能

    redis-cli我们最常用的两个参数就是-h.-p.-a选项,分配用来指定连接的redis-server的host和port. 通过redis-cli –help发现,redis-cli还提供了其他 ...

  5. XMind十大最有用的功能

    XMind十大最有用的功能 XMind是一款顶级商业品质的思维导图软件和头脑风暴软件,在企业和教育领域都有很广泛的应用,XMind功能全面,易上手,在此小编给大家整理出了XMind十大最有用的功能以供 ...

  6. 在网站开发中很有用的8个 jQuery 效果【附源码】

    jQuery 作为最优秀 JavaScript 库之一,改变了很多人编写 JavaScript 的方式.它简化了 HTML 文档遍历,事件处理,动画和 Ajax 交互,而且有成千上万的成熟 jQuer ...

  7. 对于 Web 开发很有用的 jQuery 效果制作教程

    如果你的项目中需要响应式滑块,炫丽的图片呈现,对话框提示,轻巧动画等效果,jQuery 是完美的解决方案.凭借这个快速,易用的 JavaScript 库,可以轻松处理语言之间的交互,它给人最快速的 W ...

  8. 今日推荐:10款在 Web 开发中很有用的占位图片服务

    设计网站时,将要使用的图像在一开始通常还不存在,这个时候布局是最重要的.然而,图像的尺寸通常是预先设置,实用一些占位图像可以帮助我们更好地预览和分析布局. 如今,有免费的占位图片自动生成工具可以使用, ...

  9. 继承自NSObject的不常用又很有用的函数(2)

    函数调用 Objective-C是一门动态语言,一个函数是由一个selector(SEL),和一个implement(IML)组成的.Selector相当于门牌号,而Implement才是真正的住户( ...

随机推荐

  1. ASP.NET MVC分页 Ajax+JsRender

    前段时间整mvc的分页,倒是很顺利,参考了以下几篇博客,启发很大. http://www.cnblogs.com/tangmingjun/archive/2012/05/30/2526301.html ...

  2. [数据结构]最小生成树算法Prim和Kruskal算法

    最小生成树 在含有n个顶点的连通图中选择n-1条边,构成一棵极小连通子图,并使该连通子图中n-1条边上权值之和达到最小,则称其为连通网的最小生成树.  例如,对于如上图G4所示的连通网可以有多棵权值总 ...

  3. shell将字符串分隔成数组

    #!/bin/bash a="hello,world,nice,to,meet,you" #要将$a分割开,先存储旧的分隔符 OLD_IFS="$IFS" #设 ...

  4. 解决mysql开启GTID主从同步出现1236错误问题

    解决mysql开启GTID主从同步出现1236错误问题     最近遇到mysql开启gtid做复制时,从库出现1236错误,导致同步无法进行,本文就这问题记录下处理步骤,有关gtid知识在这里不做介 ...

  5. 利用SpringCloud搭建一个最简单的微服务框架

    http://blog.csdn.net/caicongyang/article/details/52974406 1.微服务 微服务主要包含服务注册,服务发现,服务路由,服务配置,服务熔断,服务降级 ...

  6. click只能点击一次

    <select id="s_province" name="s_province" class="s_province">< ...

  7. loadrunner 性能测试报error-27796的解决

    网上观点: 在注册表HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Tcpip/Parameters里,有如下两个键值:TcpTimedWai ...

  8. ASP.NET中使用JavaScript实现图片自动水平滚动效果

    参照网上的资料,在ASP.NET中使用JavaScript实现图片自动水平滚动效果. 1.页面前台代码: <%@ Page Language="C#" AutoEventWi ...

  9. Android Studio错误提示:Gradle project sync failed. Basic functionality (eg. editing, debugging) will not work properly

    Android Studio中出现提示: Gradle project sync failed. Basic functionality (eg. editing, debugging) will n ...

  10. 关于Unity中Shader的使用

    在游戏的开发过程中,程序员不太会自己去写shader,因为写起来很麻烦,而且只有Unity会报错,编译器也没有什么提示. 通常是拿别人的shader改一改,当然,程序员还是要能看懂和会一点shader ...