本文實例講述了PHP實現(xiàn)動態(tài)獲取函數(shù)參數(shù)的方法。分享給大家供大家參考,具體如下:
PHP 在用戶自定義函數(shù)中支持可變數(shù)量的參數(shù)列表。其實很簡單,只需使用 func_num_args()
, func_get_arg()
,和 func_get_args()
函數(shù)即可。
可變參數(shù)并不需要特別的語法,參數(shù)列表仍按函數(shù)定義的方式傳遞給函數(shù),并按通常的方式使用這些參數(shù)。
1. func_num_args — 返回傳入函數(shù)的參數(shù)總個數(shù)
int func_num_args ( void )
示例
?php function demo () { $numargs = func_num_args (); echo "參數(shù)個數(shù)為: $numargs \n" ; } demo ( 'a' , 'b' , 'c' );
運行結果
參數(shù)個數(shù)為: 3
2. func_get_args — 返回傳入函數(shù)的參數(shù)列表
array func_get_args ( void )
示例
?php function demo () { $args = func_get_args(); echo "傳入的參數(shù)分別為:"; var_dump($args); } demo ( 'a' , 'b' , 'c' );
運行結果
傳入的參數(shù)分別為:
array (size=3)
0 => string 'a' (length=1)
1 => string 'b' (length=1)
2 => string 'c' (length=1)
3. func_get_arg — 根據(jù)參數(shù)索引從參數(shù)列表返回參數(shù)值
mixed func_get_arg ( int $arg_num )
示例
?php function demo () { $numargs = func_num_args (); echo "參數(shù)個數(shù)為: $numargs br />" ; $args = func_get_args(); if ( $numargs >= 2 ) { echo "第二個參數(shù)為: " . func_get_arg ( 1 ) . "br />" ; } } demo ( 'a' , 'b' , 'c' );
運行結果
參數(shù)個數(shù)為: 3
第二個參數(shù)為: b
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php常用函數(shù)與技巧總結》、《php字符串(string)用法總結》、《PHP數(shù)據(jù)結構與算法教程》、《php程序設計算法總結》及《PHP數(shù)組(Array)操作技巧大全》
希望本文所述對大家PHP程序設計有所幫助。
上一篇:PHP調用其他文件中的類