1.用引用傳遞函數參數
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;
?>
<?php
function add_some_extra(&$string)
{
$string = 'and something extra.';
}
add_some_extra($string);
echo $string;
2.可變數量的參數列表
In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; 轉化爲數組
for example:
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
應用場景,當我們不清楚具體傳參長度時,可以使用;例如寫日誌,不同日誌需要參數不同
<?php
function out_log(string $msg, string ...$rep)
{
array_unshift($rep, $msg);
$log = count($rep)>=2 ? call_user_func_array('sprintf', $rep) : $msg;
echo $log;
}
out_log('%s報錯了;在%s','遊戲過程中',date('Y-m-d H:i:s'));
out_log('%s不小心觸發了%s,在%s', 'Marry', 'WARNING WARNING',date('Y-m-d H:i:s'));
?>