Current Location: Home> Latest Articles> Detailed Explanation and Restrictions of PHP Function Parameter Passing

Detailed Explanation and Restrictions of PHP Function Parameter Passing

M66 2025-07-17

PHP Function Parameter Passing Methods and Their Restrictions

The Two Parameter Passing Methods

In PHP, there are two primary ways to pass function parameters:

  • Pass by Value: The function receives a copy of the parameter, and any changes made inside the function do not affect the original variable outside.
  • Pass by Reference: The function receives a reference to the variable, so changes inside the function affect the original variable.

Restrictions on Parameter Passing

Regarding pass by reference, PHP imposes the following restrictions:

  • Only variables can be passed by reference; constants or expressions cannot be passed directly.
  • The variable passed by reference must be assigned a value; otherwise, an error will occur if not assigned inside the function.

Example Demonstrations

Pass by Value Example

function sum(int $num1, int $num2) {
  $result = $num1 + $num2;
  return $result;
}

$a = 5;
$b = 10;

$result = sum($a, $b); // $result is 15; $a and $b remain unchanged

Pass by Reference Example

function swap(int &$num1, int &$num2) {
  $temp = $num1;
  $num1 = $num2;
  $num2 = $temp;
}

$a = 5;
$b = 10;

swap($a, $b); // $a becomes 10; $b becomes 5

Summary

Understanding PHP function parameter passing methods and their restrictions is essential for writing efficient and error-free code. Pass by value is suitable when protecting external variables, while pass by reference allows direct modification of external variables but requires that the variables be assigned beforehand.