PHP开发的程序员应该清楚,PHP中有很多内置的功能,掌握了它们,可以帮助你在做PHP开发时更加得心应手,本文将分享8个开发必备的PHP功能,个个都非常实用,希望各位PHP开发者能够掌握。
1、传递任意数量的函数参数
我们在.NET或者JAVA编程中,一般函数参数个数都是固定的,但是PHP允许你使用任意个数的参数。下面这个示例向你展示了PHP函数的默认参数:
// 两个默认参数的函数 function foo($arg1 = ”, $arg2 = ”) { echo “arg1: $arg1/n”; echo “arg2: $arg2/n”; } foo(‘hello','world'); /* 输出:arg1: helloarg2: world*/ foo(); /* 输出:arg1:arg2:*/
下面这个示例是PHP的不定参数用法,其使用到了 func_get_args()方法:
// 是的,形参列表为空 function foo() { // 取得所有的传入参数的数组 $args = func_get_args(); foreach ($args as $k => $v) { echo “arg”.($k+1).”: $v/n”; } } foo(); /* 什么也不会输出 */ foo(‘hello'); /* 输出arg1: hello*/ foo(‘hello', ‘world', ‘again'); /* 输出arg1: helloarg2: worldarg3: again*/
2、使用glob()查找文件
大部分PHP函数的函数名从字面上都可以理解其用途,但是当你看到 glob() 的时候,你也许并不知道这是用来做什么的,其实glob()和scandir() 一样,可以用来查找文件,请看下面的用法:
// 取得所有的后缀为PHP的文件 $files = glob(‘*.php'); print_r($files); /* 输出: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); /* 输出:Array([0] => phptest.php[1] => pi.php[2] => post_output.php[3] => test.php[4] => log.txt[5] => test.txt13.)*/
你还可以加上路径:
$files = glob(‘../images/a*.jpg'); print_r($files); /* 输出:Array([0] => ../images/apple.jpg[1] => ../images/art.jpg)*/
如果你想得到绝对路径,你可以调用 realpath() 函数:
$files = glob(‘../images/a*.jpg'); // applies the function to each array element $files = array_map(‘realpath',$files); print_r($files); /* output looks like:Array([0] => C:/wamp/www/images/apple.jpg[1] => C:/wamp/www/images/art.jpg)*/
3、获取内存使用情况信息
PHP的内存回收机制已经非常强大,你也可以使用PHP脚本获取当前内存的使用情况,调用memory_get_usage() 函数获取当期内存使用情况,调用memory_get_peak_usage() 函数获取内存使用的峰值。参考代码如下:
echo “Initial: “.memory_get_usage().” bytes /n”; /* 输出Initial: 361400 bytes*/ // 使用内存 for ($i = 0; $i < 100000; $i++) { $array []= md5($i); } // 删除一半的内存 for ($i = 0; $i < 100000; $i++) { unset($array[$i]); } echo “Final: “.memory_get_usage().” bytes /n”; /* printsFinal: 885912 bytes*/ echo “Peak: “.memory_get_peak_usage().” bytes /n”; /* 输出峰值Peak: 13687072 bytes*/
新闻热点
疑难解答