PHP程序员要知道的几个有用的PHP函数

PHP为PHP程序员提供了很多好用的函数,让 php程序员 能民快速地完成程序的开发和调试,看看这几个 php 函数的用法,你知道吗?


1. 内存使用情况 memory_get_usage()
注意程序的内存使用情况,能让PHP程序员更好的优化自己的PHP程序。

PHP有自己的垃圾回收机制,同时也有很复杂的内存管理机制。PHP程序员可以通过memory_get_usage()函数看观察自己的PHP程序的内存使用情况,示例代码如下:
echo '开始:' . memory_get_usage() . 'bytes \n'; 
$str = str_repeat('Hello world', 1234); 
echo memory_get_usage() . 'bytes \n'; 
unset($str); 
echo memory_get_usage() . 'bytes \n'; 

echo '内存使用峰值为:' . memory_get_peak_usage() . 'bytes \n';

注:若用 memory_get_usage(true) 则是显示不包括此函数所占的内存,和linux中
ll | grep str | grep -v grep 的-v类似

相关的函数还有 getrusage() 用于得到 cpu的使用情况
php.net 中的示例代码如下:
$dat = getrusage(); 
echo $dat["ru_nswap"];         // number of swaps 
echo $dat["ru_majflt"];        // number of page faults 
echo $dat["ru_utime.tv_sec"];  // user time used (seconds) 
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)

2. PHP还提供了很多好用的系统常量
如:__LINE__(当前行号),__FILE__(文件路径),__DIR__(目录)
__FUNCTION__(函数名),__CLASS__(类名)

这些函数主要是用来调试的,不过也有其他的用法

如:dirname(__FILE__) 在include时,可得到当前的文件路径
__DIR__在PHP5.3后才有

3. 用 uniqid() 来生成唯一的ID
在实际的应用中这个函数很给力的

4. 字符串压缩 gzcompress()
我们会经常听说对文件进行压缩,还有用 gzip 对来优化网站
PHP为程序员提供了对字符串的压缩,不知你用过吗?
注:对应的解压函数为 gzuncompress(), 压缩比率可以达到 50%

5. 注册停止前运行函数 register_shutdown_time()
这个函数,让你在整个脚本停时前运行代码,最常用的就是获取程序的运行时间
当然还有其他的用法,下面是php.net给出的一段代码:
function shutdown_function (&$test) { 
    echo __FUNCTION__.'(): $test = '.$test."\n"; 


$test = 1; 
register_shutdown_function('shutdown_function', &$test); 
echo '$test = '.$test."\n"; 

// do some stuff and change the variable values 
$test = 2; 

// now the shutdown function gets called 
exit(0);

6. 用 glob() 来查找文件
foreach (glob("*.txt") as $filename) { 
    echo "$filename size " . filesize($filename) . "\n"; 
}

猜你喜欢

转载自blog.csdn.net/php_897721669/article/details/8876977
今日推荐