好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php函数之func_get_args()、func_get_arg()与func_num_args

php函数之func_get_args()、func_get_arg()与func_num_args()

本文章来给各位同总结一下在php中func_get_args()、func_get_arg()与func_num_args()三个函数的用法与区别对比,各位同学不防参考参考.

今天用到这个几个内置函数,记录下以便返查

func_num_args()   返回调用函数的传入参数个数,类型是整型

func_get_arg()   返回指定的参数值

func_get_args()   返回全部参数的值,类型是数组

func_get_args 返回一个包含函数参数列表的数组

描述:array func_get_args(void)

此函数返回一数组,数组的各个元素相当于是目前使用者定义函数的各个参数,如果是从函数定义的外面来呼叫此函数,则func_get_args()将会产生警告.

func_get_arg 从函数参数列表返回指定参数

描述:mixed func_get_arg( int arg_num )

传回定义函数的参数列表的第arg_num个参数,其参数从0开始,且函数定义的外面来呼叫此函数会产生警告,并且当arg_num大于函数实际传递的参数数目时亦会产生警告并返回FALSE.

func_num_args 返回传递到函数的参数数目

描述 int func_num_args( void )

此函数返回传递到目前定义函数的参数数目,如果是从函数定义的外面来呼叫此函数,则func_num_args()将会产生警告.

func_num_args()可以用来结合func_get_arg()和func_get_args(),来允许使用者定义的函数接受可变长度参数列表,在我们构建PHP类的时候,灵活使用这三个函数,可以起到非常理想的效果,例如外面在创建PHP和MYSQL链接的类时,可以书写如下代码:

<?php  class  mydb{  private   $user ;  private   $pass ;  private   $host ;  private   $db ;  public   function  __construct(){  $num_args =func_num_args();  if ( $num_args >0){  //开源代码phpfensi.com   $args =func_get_args();  $this ->host= $args [0];  $this ->user= $args [1];  $this ->pass= $args [2];  this->connect();  }  }  ……..  ?> 

下面是手册上的一个例子,代码如下:

<?php  function  foo()  {       $numargs  = func_num_args();       echo   "Number of arguments: $numargs<br />n" ;       if  ( $numargs  >= 2) {           echo   "Second argument is: "  . func_get_arg(1) .  "<br />n" ;      }       $arg_list  = func_get_args();       for  ( $i  = 0;  $i  <  $numargs ;  $i ++) {           echo   "Argument $i is: "  .  $arg_list [ $i ] .  "<br />n" ;      }  }    foo(1, 2, 3);  ?>  //输出结果是:   Number of arguments: 3  Second argument is: 2  Argument 0 is: 1  Argument 1 is: 2  Argument 2 is: 3

查看更多关于php函数之func_get_args()、func_get_arg()与func_num_args的详细内容...

  阅读:35次