Content · Web Development · PHP

PHP Reference Variables and Parameters

Reference parameters can mutate a caller's variable without returning it. Document the side effect and avoid keeping accidental foreach references.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Reference parameters can mutate a caller's variable without returning it.

What It Does


Reference parameters can mutate a caller's variable without returning it. The following examples distinguish a normal use case, a boundary case and a practical application.

Requirements and Compatibility


PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.

The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.

Example 1: Basic Behavior


Start with the smallest meaningful working case.

<?php
$a = 10; $b = &$a; $b = 15; echo $a;

Example 2: Another Case


Examine the edge case and the observable result.

<?php
$first = ['x' => 1]; $copy = $first; $copy['x'] = 9;
echo $first['x']; // Array copy-on-write

Practical Example: Putting It to Use


Reference parameters intentionally mutate the caller's variable.

<?php
function applyDiscount(int &$cents): void { $cents = (int) round($cents * .9); }
$price = 500; applyDiscount($price); echo $price;

Important Behavior and Edge Cases


Document the side effect and avoid keeping accidental foreach references alive.

Comparison with Related Functions or Approaches


OptionWhat it means in practice
Reference Variables and ParametersReference parameters can mutate a caller's variable without returning it.
Related approachImmutable return-value patterns simplify reasoning and tests.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the important boundary for Reference Variables and ParametersDocument the side effect and avoid keeping accidental foreach references alive.
Assuming a related mechanism has the same behaviorImmutable return-value patterns simplify reasoning and tests.

Key Takeaways


  • Reference parameters can mutate a caller's variable without returning it.
  • Document the side effect and avoid keeping accidental foreach references alive.
  • Immutable return-value patterns simplify reasoning and tests.

Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.

Share this resourceSend this page to someone who may find it useful.