在 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
总结: