函数
1、传递任意数量的函数参数
我们在.NET或者JAVA编程中,一般函数参数个数都是固定的,但是PHP允许你使用任意个数的参数。下面这个示例向你展示了PHP函数的默认参数:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// 两个默认参数的函数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()方法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
// 是的,形参列表为空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 */ |
2、使用glob()查找文件
大部分PHP函数的函数名从字面上都可以理解其用途,但是当你看到?glob() 的时候,你也许并不知道这是用来做什么的,其实glob()和scandir() 一样,可以用来查找文件,请看下面的用法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// 取得所有的后缀为PHP的文件$files = glob(‘*.php’);print_r($files); /* 输出:Array ( [0] => phptest.php [1] => pi.php [2] => post_output.php [3] => test.php ) */ |
你还可以查找多种后缀名
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// 取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 ) */ |
你还可以加上路径:
|
1
2
3
4
5
6
7
8
9
10
|
$files = glob(‘../images/a*.jpg’);print_r($files); /* 输出:Array ( [0] => ../images/apple.jpg [1] => ../images/art.jpg ) */ |
如果你想得到绝对路径,你可以调用?realpath() 函数:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
$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 ) */ |

浙公网安备 33010602011771号