在 PHP 中,函數參數可以通過值傳遞或引用傳遞。它們之間的主要區別在于數據如何傳遞給函數以及函數內部如何操作這些數據。以下是值傳遞和引用傳遞之間的區別:
值傳遞(Pass by Value):
function add_num($num1, $num2) {
$num1 = $num1 + $num2;
return $num1;
}
$a = 10;
$b = 20;
$c = add_num($a, $b);
echo $a . ", " . $b . ", " . $c; // 輸出 10, 20, 30
引用傳遞(Pass by Reference):
function add_num_ref(&$num1, &$num2) {
$num1 = $num1 + $num2;
return $num1;
}
$a = 10;
$b = 20;
$c = add_num_ref($a, $b);
echo $a . ", " . $b . ", " . $c; // 輸出 30, 20, 30
總結: