Home >Backend Development >PHP Tutorial >What are the differences between PHP function parameter passing methods?

What are the differences between PHP function parameter passing methods?

WBOY
WBOYOriginal
2024-04-19 21:15:02596browse

There are two ways to pass function parameters in PHP: value passing and reference passing. Value passing transfers a copy of the variable value, and modifications to the copy will not affect the original variable; reference passing transfers a reference to the variable itself, and modifications to the reference will directly affect the original variable. In form processing, value transfer can be used to obtain data, and reference transfer can be used to modify data, but the default transfer method is value transfer, and reference transfer parameters need to use the & symbol.

What are the differences between PHP function parameter passing methods?

PHP function parameter passing method

PHP function parameter passing method is divided into two types: reference passing and value passing.

Value passing

In value passing, the function receives a copy of the variable value. Modifications to the copy do not affect the original variable.

function changeValue($num) {
  $num = 10;
}

$num = 5;
changeValue($num);

echo $num; // 输出 5

Pass by reference

In pass by reference, the function receives a reference to the variable itself. Modifications to the reference directly affect the original variable.

function changeValueByReference(&$num) {
  $num = 10;
}

$num = 5;
changeValueByReference($num);

echo $num; // 输出 10

Practical case

In form processing, we often need to obtain the data submitted by the form. Value passing can be used to obtain form data, but if we want to modify the form data, we need to use reference passing.

<form action="process_form.php" method="post">
  <input type="text" name="name">
  <input type="submit">
</form>
// process_form.php
<?php
function processForm($name) {
  // 对 $name 进行修改
  $name = strtoupper($name);
}

$name = $_POST['name'];
processForm($name);

echo $name; // 输出大写后的用户名
?>

Note:

  • The default passing method of function parameters is value passing.
  • Parameters passed by reference must use the & symbol.
  • Use pass-by-reference with caution, as unintended modifications to references may have unintended consequences.

The above is the detailed content of What are the differences between PHP function parameter passing methods?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn