func_get_args和foreach

时间:2012-12-16 12:43:40

标签: php

这两者之间有什么不同, 为什么我使用func_get_args foreach只回显最后一个数字" 7"

function add(){
    $total=func_get_args();
    foreach($total as $result);
    echo $result;
    }

add(1, 5 , 6, 7);

//////////////////////////////////////////////////////////////////

$array=array(1, 5, 6, 7);
foreach($array as $result){
    echo $result;
    }

2 个答案:

答案 0 :(得分:3)

中删除分号
foreach($total as $result);

应该是

foreach($total as $result)

答案 1 :(得分:3)

首先,你对foreach循环没有任何作用

foreach ($total as $result) /* nothing */ ;

发生了什么事情,最后$result被遗留下来并被下一行回应。

你实际上可以像这样重写add函数:

function add(){
    return array_sum(func_get_args());
}

echo add(1, 5 , 6, 7);

哪个是更酷的imho;)(但不检查字符串值等)