8 个必备的PHP功能开发
1、传递任意数量的函数参数
我们在.NET或者JAVA编程中,一般函数参数个数都是固定的,但是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: 15 */ 16 下面这个示例是PHP的不定参数用法,其使用到了 func_get_args()方法: 17 // 是的,形参列表为空 18 function foo() { 19 // 取得所有的传入参数的数组 20 $args = func_get_args(); 21 foreach ($args as $k => $v) { 22 echo “arg”.($k+1).”: $v\n”; 23 } 24 } 25 foo(); 26 /* 什么也不会输出 */ 27 foo(‘hello’); 28 /* 输出 29 arg1: hello 30 */ 31 foo(‘hello’, ‘world’, ‘again’); 32 /* 输出 33 arg1: hello 34 arg2: world 35 arg3: again 36 */
2、使用glob()查找文件
大部分PHP函数的函数名从字面上都可以理解其用途,但是当你看到 glob() 的时候,你也许并不知道这是用来做什么的,其实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 */
如果你想得到绝对路径,你可以调用 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 */