請寫一個php函數,可以接受任意數量的參數


請寫一個php函數,可以接受任意數量的參數

這是一道面試題。怎么寫這個函數呢?

 

function fun(......)

{

 

 

}

 

-----------------------------------------解決方案------------------------------

//PHP code

 

show_params(1, 2, 'apple', 3.14);

function show_params () {

    //獲取傳遞參數的個數

    $count = func_num_args();

 

    //遍歷參數並逐一輸出

    for ($i = 0; $i < $count; $i++) {

      //獲取參數

      $param = func_get_arg($i);

      echo $param . PHP_EOL;

    }

  }

 

-----------------------------------------解決方案------------------------------

//PHP code

 

function func()

{

var_dump(func_get_args());

}

————————————————分割線————————————————————————

實例如下:

function foo(){

//函數func_get_args():返回的是包含當前函數的所有參數的一個數組;

$args = func_get_args();

foreach($args as $k => $v){

echo 'arg'.($k+1)." : $v".'<br/>';

}

}

//沒有參數,什么都不輸出

echo foo();

//輸入 hello world

echo foo('hello ', 'world');

 

輸出

arg1 : hello

arg2 : world

 

//輸入 hello world again

echo foo('hello ', 'world', 'again');

 

輸出

arg1 : hello

arg2 : world

arg3 : again

 

 

擴展

func_num_args():返回當前函數參數的個數

func_get_arg():返回當前函數指定參數的值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM