PHP - 按值传递
默认情况下,PHP 使用“按值传递”机制将参数传递给 function。当调用 function 时,实际参数的值会被复制到 function 定义中的形参。
在执行 function 体期间,如果任何形参的值发生变化,不会反映到实际参数中。
PHP 函数中的参数类型
PHP 函数中使用以下两种类型的参数 −
实际参数 − 在 function 调用中传递的参数。
形参 − 在 function 定义中声明的参数。
Syntax
以下是在 PHP 中定义实际参数和形参的方式:
<?php
// $name 是形参
function greet($name) {
echo "Hello, $name!";
}
// Rahul 是实际参数
greet("Rahul");
?>
演示按值传递
让我们考虑下面代码中使用的 function −
<?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";
?>
Output
它将产生以下结果 −
My name is John Initially the name is John This function changes the name to John_new My name is still John
在这个例子中,change_name() function 将_new追加到传递给它的字符串参数。然而,传递给它的变量的值在 function 执行后保持不变。
事实上,形参在 function 中表现为 local variables。此类变量仅在其初始化作用域内可访问。对于 function,其由大括号 "{ }" 标记的体就是其作用域。此作用域内的任何变量都无法被外部代码访问。因此,对任何 local variable 的操作不会影响外部世界。
“按值传递”方法适用于使用传递给它的值的 function。它执行某些计算并返回结果,而无需更改传递给它的参数值。
注意 − 执行公式型计算的任何 function 都是按值传递的示例。
Example 1
查看以下示例 −
<?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";
?>
Output
它将生成以下输出 −
Sum of the two numbers is : 30
Example 2
这是另一个按值传递参数调用 function 的示例。该 function 将接收到的数字加 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";
?>
Output
它将产生以下结果 −
The initial value: 10 This function increments the number by 1 to 11 Number has not changed: 10
Example 3
在下面的示例中,我们将递增一个值,但不会更改原始变量。
<?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";
?>
Output
它将生成以下结果 −
The initial value: 10 This function increments the number by 1 to 11 Number has not changed: 10
值传递中的字符串操作
在 PHP 中,我们也可以使用值传递来操作字符串。在我们的示例中,我们将通过在参数中传递值来追加字符串。
<?php
function appendString($str) {
$str .= " World!";
echo "Inside function: $str\n";
}
$text = "Hello";
appendString($text);
// 原始字符串保持不变
echo "Outside function: $text";
?>
输出
它将生成以下结果 −
Inside function: Hello World! Outside function: Hello
PHP 还支持在调用函数时传递变量的引用。我们将在下一章讨论这一点。