php實現函式可變引數列表

scutwang發表於2013-07-27

使用func_get_args()func_num_args()func_get_arg() 可以構造一個可變引數列表的函式。

首先大致介紹以上三個函式。

(1)array func_get_args ( void )

說明:函式傳回一陣列,陣列的各個元素相當於是目前使用者定義函式的引數列的數目

(2)int func_num_args ( void )

說明 : 返回傳遞到目前定義函式的引數數目。如果是從函式定義的外面來呼叫此函式,則func_get_arg( )將會產生警告。

(3)mixed func_get_arg ( int $arg_num )

說明 :傳回定義函式的引數列表的第arg_num個引數,其引數從0開始。且函式定義的外面來呼叫此函式會產生警告,且當arg_num大於函式實際傳遞的引數數目時亦會產生警告並返回FALSE。

 

示例:

<?php
/**
* 函式的多引數列表的實現
*
*/
function multiArgs()
{
/** 以陣列的形式返回引數列表 */
    $args = func_get_args();
    /** 引數的個數 */
    $args_num = func_num_args();
    foreach ( $args as $key => $value )
    {
        echo 'This is '.($key+1).'th argument,'.$value.'<br/>';
    }
    echo 'Number of args is '.$args_num;
} multiArgs(‘one’
,'two’,'three’); /** output */ /** This is 1th argument:one This is 2th argument:two This is 3th argument:three Number of args is 3 */ ?>

 

相關文章