日期:2014-05-17  浏览次数:20438 次

9个你需要知道的PHP函数和功能
即使使用 PHP 多年,有些功能和特点我们也未必发现或未被充分利用,一旦被我们发现,就会发现它们非常有用。然而,并不是所有的人都已经从头至尾详读过 PHP 的手册和功能参考!

1. 函数与任意数量的参数
您可能已经知道,PHP 允许我们定义可选参数的函数。但也有完全允许任意数量的函数参数方法。

首先,下面这个例子只是可选参数:

view sourceprint?01 // function with 2 optional arguments 

02 function foo($arg1 = '', $arg2 = '') { 

03     echo "arg1: $arg1\n"; 

04     echo "arg2: $arg2\n"; 

05 } 

06 foo('hello','world'); 

07 /* prints: 

08 arg1: hello 

09 arg2: world 

10 */

11 foo(); 

12 /* prints: 

13 arg1: 

14 arg2: 

15 */

现在,让我们看看如何可以建立一个函数接受任何数量的参数。这一次,我们要利用 func_get_args() 函数:

view sourceprint?01 // yes, the argument list can be empty 

02 function foo() { 

03     // returns an array of all passed arguments 

04     $args = func_get_args(); 

05     foreach ($args as $k => $v) { 

06         echo "arg".($k+1).": $v\n"; 

07     } 

08 } 

09 foo(); 

10 /* prints nothing */

11 foo('hello'); 

12 /* prints 

13 arg1: hello 

14 */

15 foo('hello', 'world', 'again'); 

16 /* prints 

17 arg1: hello 

18 arg2: world 

19 arg3: again 

20 */

2. 使用 Glob() 函数来查找文件
许多 PHP 内置函数有非常长的命名。然而,它可能会很难说明是什么作用的函数,如果不使用 Glob() 来做,除非你已经非常熟悉这个函数。

它更像是 scandir() 函数加强型版本。它可以让您通过使用模式搜索文件。

view sourceprint?01 // get all php files 

02 $files = glob('*.php'); 

03 print_r($files); 

04 /* output looks like: 

05 Array 

06 ( 

07     [0] => phptest.php 

08     [1] => pi.php 

09     [2] => post_output.php 

10     [3] => test.php 

11 ) 

12 */

这样你可以获得多个文件类型:

view sourceprint?01 // get all php files AND txt files 

02 $files = glob('*.{php,txt}', GLOB_BRACE); 

03 print_r($files); 

04 /* output looks like: 

05 Array 

06 ( 

07     [0] => phptest.php 

08     [1] => pi.php 

09     [2] => post_output.php 

10     [3] => test.php 

11     [4] => log.txt 

12     [5] => test.txt 

13 ) 

14 */

请注意,这些文件其实是可以返回一个路径的,根据你的查询。

view sourceprint?1 $files = glob('../images/a*.jpg'); 

2 print_r($files); 

3 /* output looks like: 

4 Array 

5 ( 

6     [0] => ../images/apple.jpg 

7     [1] => ../images/art.jpg 

8 ) 

9 */

如果你想获得每个文件的完整路径,你可以调用 realpath() 函数来返回。

view sourceprint?01 $files = glob('../images/a*.jpg'); 

02 // applies the function to each array element 

03 $files = array_map('realpath',$files); 

04 print_r($files); 

05 /* output looks like: 

06 Array 

07 (