Current Location: Home> Latest Articles> PHP Function Parameter Passing Methods Explained: Value Passing vs Reference Passing

PHP Function Parameter Passing Methods Explained: Value Passing vs Reference Passing

M66 2025-10-02

PHP Function Parameter Passing Methods Explained

In PHP, there are two ways to pass function parameters: value passing and reference passing. These two methods have fundamental differences, and understanding them is essential for developers to write efficient and stable code.

Value Passing

Value passing means that a copy of the parameter is passed when calling the function. Modifying the copy inside the function does not affect the original variable. Value passing is suitable for situations where the function only needs to read the parameter's data.

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

$num = 5;
changeValue($num);

echo $num; // Output 5

As shown above, the function changeValue accepts a variable and modifies it to 10, but the original value of $num remains 5 outside the function.

Reference Passing

Unlike value passing, reference passing passes the actual reference of the variable. This means that modifying the parameter inside the function will directly affect the original variable.

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

$num = 5;
changeValueByReference($num);

echo $num; // Output 10

In this example, the function changeValueByReference modifies the passed $num variable, causing the original variable's value to become 10.

Real-World Application

In real-world development, especially in form processing, both value passing and reference passing are commonly used in PHP. Value passing is often used to retrieve form data, while reference passing is used when we need to modify the form data.

<form action="process_form.php" method="post">
    <input type="text" name="name">
    <input type="submit">
</form>
// process_form.php
function processForm(&$name) {
    // Modify $name
    $name = strtoupper($name);
}

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

echo $name; // Output the uppercase username

As shown above, when processing a form submission, we use reference passing to modify the $name parameter, which helps us process the submitted data, such as converting it to uppercase.

Notes

  • The default parameter passing method in PHP is value passing.
  • Reference passing requires the use of the & symbol.
  • Although reference passing is convenient, it should be used carefully to avoid accidentally modifying the original variables.

This article covered the basic concepts of PHP function parameter passing methods. Understanding these differences can help developers handle data more flexibly and efficiently in their projects.