php函數特殊應用

1.用引用傳遞函數參數

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

<?php
function add_some_extra(&$string)
{
    $string = 'and something extra.';
}
add_some_extra($string);//只有變量才能使用引用,不能傳$string = 'aaa',這是表達式
echo $string;    // outputs 'and something extra.'

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'));
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章