默认情况下,PHP 使用 “call by value” 机制将参数传递给函数。调用函数时,实际参数的值将复制到函数定义的正式参数中。
在函数体的执行过程中,如果任何形式参数的值有任何变化,则不会反映在实际参数中。
- 实际参数: 在函数调用中传递的参数。
- 形式参数: 在函数定义中声明的参数。
例
让我们考虑一下下面代码中使用的函数 -
<?php
function change_name($nm) {
echo "Initially the name is $nm \n";
$nm = $nm."_new";
echo "This function changes the name to $nm \n";
}
$name = "John";
echo "My name is $name \n";
change_name($name);
echo "My name is still $name";
?>
它将产生以下输出 -
My name is John
Initially the name is John
This function changes the name to John_new
My name is still John
Initially the name is John
This function changes the name to John_new
My name is still John
在此示例中,change_name() 函数将 _new 附加到传递给它的 string 参数。但是,在函数执行后,传递给它的变量的值保持不变。
实际上,形式参数的行为与函数的局部变量相同。此类变量只能在初始化它的范围内访问。对于函数,由大括号 “{ }” 标记的主体是其范围。此作用域内的任何变量都不适用于其作用域外的代码。因此,对任何局部变量的操纵都不会影响外部世界。
“按值调用”方法适用于使用传递给它的值的函数。它执行某些计算并返回结果,而无需更改传递给它的参数的值。
注意: 任何执行公式类型计算的函数都是按值调用的示例。
例
请看下面的例子 -
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$x = 10;
$y = 20;
$num = addFunction($x, $y);
echo "Sum of the two numbers is : $num";
?>
它将产生以下输出 -
Sum of the two numbers is : 30
例
这是另一个通过按值传递参数来调用函数的示例。该函数将收到的数字递增 1,但这不会影响传递给它的变量。
<?php
function increment($num) {
echo "The initial value: $num \n";
$num++;
echo "This function increments the number by 1 to $num \n";
}
$x = 10;
increment($x);
echo "Number has not changed: $x";
?>
它将产生以下输出 -
The initial value: 10
This function increments the number by 1 to 11
Number has not changed: 10
This function increments the number by 1 to 11
Number has not changed: 10
PHP 还支持在调用时将变量的引用传递给函数。我们将在下一章中讨论它。