本文實例講述了PHP實現動態獲取函數參數的方法。分享給大家供大家參考,具體如下:
PHP 在用戶自定義函數中支持可變數量的參數列表。其實很簡單,只需使用 func_num_args()
, func_get_arg()
,和 func_get_args()
函數即可。
可變參數并不需要特別的語法,參數列表仍按函數定義的方式傳遞給函數,并按通常的方式使用這些參數。
1. func_num_args — 返回傳入函數的參數總個數
int func_num_args ( void )
示例
<?php function demo () { $numargs = func_num_args (); echo "參數個數為: $numargs \n" ; } demo ( 'a' , 'b' , 'c' );
運行結果
參數個數為: 3
2. func_get_args — 返回傳入函數的參數列表
array func_get_args ( void )
示例
<?php function demo () { $args = func_get_args(); echo "傳入的參數分別為:"; var_dump($args); } demo ( 'a' , 'b' , 'c' );
運行結果
傳入的參數分別為:
array (size=3)
0 => string 'a' (length=1)
1 => string 'b' (length=1)
2 => string 'c' (length=1)
3. func_get_arg — 根據參數索引從參數列表返回參數值
mixed func_get_arg ( int $arg_num )
示例
<?php function demo () { $numargs = func_num_args (); echo "參數個數為: $numargs <br />" ; $args = func_get_args(); if ( $numargs >= 2 ) { echo "第二個參數為: " . func_get_arg ( 1 ) . "<br />" ; } } demo ( 'a' , 'b' , 'c' );
運行結果
參數個數為: 3
第二個參數為: b
希望本文所述對大家PHP程序設計有所幫助。