做过PHP开发的程序员应该清楚,PHP中有很多内置的功能,掌握了它们,可以帮助你在做PHP开发时更加得心应手,本文将分享8个开发必备的PHP功能,个个都非常实用,希望各位PHP开发者能够掌握。
我们在.NET或者java编程中,一般函数参数个数都是固定的,但是PHP允许你使用任意个数的参数。下面这个示例向你展示了PHP函数的默认参数:
12345678910111213141516171819 | // 两个默认参数的函数 function foo( $arg1 = ”, $arg2 = ”) { echo “arg1: $arg1 /n”; echo “arg2: $arg2 /n”; } foo(‘hello’,'world’);
/* 输出: arg1: hello
arg2: world
*/ foo();
/* 输出: arg1:
arg2:
*/ |
下面这个示例是PHP的不定参数用法,其使用到了?func_get_args()方法:
1234567891011121314151617181920212223242526 | // 是的,形参列表为空 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: hello
arg2: world
arg3: again
*/ |
大部分PHP函数的函数名从字面上都可以理解其用途,但是当你看到?glob()的时候,你也许并不知道这是用来做什么的,其实glob()和scandir()一样,可以用来查找文件,请看下面的用法:
12345678910111213 | // 取得所有的后缀为PHP的文件 $files = glob (‘*.php’); PRint_r( $files );
/* 输出: Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/ |
你还可以查找多种后缀名
123456789101112131415 | // 取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.txt
)
*/ |
你还可以加上路径:
12345678910 | $files = glob (‘../images/a*.jpg’); print_r( $files );
/* 输出: Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/ |
如果你想得到绝对路径,你可以调用?realpath()函数:
12345678910111213 | $files = glob (‘../images/a*.jpg’); // applies the function to each array element
$files = array_map (‘ realpath ’, $files ); print_r( $files );
/* output looks like:
|