Home > Article > Backend Development > What are the differences between PHP function parameter passing methods?
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.
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:
&
symbol. 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!