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

来源:互联网 发布:mac上电话轰炸 编辑:程序博客网 时间:2024/06/02 08:56
header('Content-type:text/html;charset=utf-8');function foo(){    $numargs = func_num_args();    //返回调用函数的传入参数个数,类型是整型    echo 'Number of arguments: '.$numargs.'<br>';    if( $numargs >= 2 )    {        echo 'Second argument is: '.func_get_arg(1).'<br>';        //传回定义函数的参数列表的第arg_num个参数,其参数从0开始。且函数定义的外面来呼叫此函数会产生警告;并且当arg_num大于函数实际传递的参数数目时亦会产生警告并返回FALSE    }    $arg_list = func_get_args();    //此函数返回一数组,数组的各个元素相当于是目前使用者定义函数的各个参数。如果是从函数定义的外面来呼叫此函数,则func_get_args()将会产生警告。    for( $i=0;$i<$numargs;$i++ )    {        echo 'Argument '.$i.' is: '.$arg_list[$i].'<br>';    }}foo(1,2,3);//func_num_args()可以用来结合func_get_arg()func_get_args(),来允许使用者定义的函数接受可变长度参数列表。在我们构建PHP类的时候,灵活使用这三个函数,可以起到非常理想的效果class mydb{    private $user;    private $pass;    private $host;    private $db;    public function __construct()    {        $num_args = func_num_args();        if ($num_args > 0) {            $args = func_get_args();            $this->host = $args[0];            $this->user = $args[1];            $this->pass = $args[2];            this->connect();        }    }}//求平均值(动态)function average(){    return array_sum(func_get_args())/func_num_args();}print average(10, 15, 20, 25); // 17.5
0 0
原创粉丝点击