7个有用的php函数

By | 2013/02/25

之前收藏的一篇文章,9 Useful PHP Functions and Features You Need to Know,感觉还不错,一些函数也是自己不常用但是确实有必要知道的,这里翻译成中文的跟大家分享:

1.函数可以接受任意数量参数

// 参数可以为空哦
function foo() {  
    // 返回一个包含所有参数的数组
    $args = func_get_args();  
    foreach ($args as $k => $v) {  
        echo "arg".($k+1).": $v\n";  
    }  
}  
foo();  
/* prints nothing */  
foo('hello');  
/* prints 
arg1: hello 
*/  
foo('hello', 'world', 'again');  
/* prints 
arg1: hello 
arg2: world 
arg3: again 
*/

func_get_args很巧妙的函数,与之对应的是func_num_arg(),可以获取参数的数目。

2.使用glob()查找指定的文件

// 得到所有的php文件
$files = glob('*.php');  
print_r($files);  
/* output looks like: 
Array 
( 
    [0] => phptest.php 
    [1] => pi.php 
    [2] => post_output.php 
    [3] => test.php 
) 
*/

复杂点的用法,指定的多个文件类型用法:

// 得到php和txt后缀的文件
$files = glob('*.{php,txt}', GLOB_BRACE);  
print_r($files);  
/* output looks like: 
Array 
( 
    [0] => phptest.php 
    [1] => pi.php 
    [2] => post_output.php 
    [3] => test.php 
    [4] => log.txt 
    [5] => test.txt 
) 
*/

3.array_map(‘function’,$array)对$array数组的值用function函数处理,最后返回一个数组


4.内存和CPU使用信息
echo “php占用内存量: “.memory_get_usage().” bytes \n”;
echo “php占用内存峰值: “.memory_get_peak_usage().” bytes \n”;
print_r(getrusage()); //cpu使用信息

5.魔术常量
当前行号:__LINE__
文件路径:__FILE__
当前目录:__DIR__
函数名:__FUNCTION__
类名:__CLASS__
方法名:__METHOD__
命名空间:__NAMESPACE__

6.获取唯一id

echo md5(time().mt_rand(1,1000000));
// with prefix  
echo uniqid('foo_');  
/* prints 
foo_4bd67d6cd8b8f 
*/  
// with more entropy  
echo uniqid('',true);  
/* prints 
4bd67d6cd8b926.12135106 
*/  
// both  
echo uniqid('bar_',true);  
/* prints 
bar_4bd67da367b650.43684647 
*/

7.序列化
serialize()可以使变量序列化后存到数据库中,unserialize()解析返回原来的变量。我的经验是尽量保存临时性的数据。因为当我们导出sql文件用作备份的时候,因为序列化后的内容带有引号容易导致sql执行失败,当然也跟导出工具有很大的关系。但是最好也是尽量避免。

最后俩感觉实在没啥用就不翻译了,没事看看php手册还是不错的,有很多新奇的函数等着我们去发掘!

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据