php函数特殊应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z15818264727/article/details/80945438

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')); ?>

猜你喜欢

转载自blog.csdn.net/z15818264727/article/details/80945438
今日推荐