In this chapter
We'll learn what happens to a value when you pass it to a function — PHP passes copies by default — how an & in the parameter list lets a function change the caller's variable, which built-in functions take references, and why a helper that changed the booking in place added the holiday surcharge twice.
The Problem in Real Life
The checkout has two steps. The preview shows the price; "Pay" charges it. Both call the same helper, applyHolidaySurcharge(array &$booking), which adds 10% to $booking["pence"]. Someone wrote it with an & so it "wouldn't copy the array".
Daniel's booking started at 2750 pence. The preview made it 3025 and showed £30.25 — correct. Then "Pay" called the helper again on the same booking, which was now 3025, and charged 3327: £33.27.
The preview only wanted to show the price. How did it change the booking?
Mia
Working on a Copy vs. Working on the Original
Copies by default
A function normally gets a copy of each argument. Whatever it does, the caller's variable stays the same.
& shares the variable
With & in the parameter, the function works on the caller's variable itself — every change sticks.
Run twice, change twice
A function that changes its input in place does it again on every call. Returning a new value doesn't.
Pass by Value vs Pass by Reference
What a function receives: Act 03 introduced references and Act 08 showed that arrays are values. Here's what that means for function calls:
- Pass by value: the default — the function gets its own copy.
- Pass by reference: with
&, the function gets the caller's variable. - When references are right: a few built-in functions, and very few of your own.
Pass by value: by default, PHP passes every argument by value: the parameter is a new variable holding a copy of the argument. Change the parameter inside the function — add to a number, add an item to an array — and the caller's variable doesn't notice. That's what makes functions safe to call: calculatePrice($booking) can't damage $booking. Copying a big array costs almost nothing, thanks to copy-on-write (Act 08): PHP only really copies when the function changes it.
<?phpdeclare(strict_types=1);function withHolidaySurcharge(int $pence): int{$pence += intdiv($pence * 10, 100); // changes the function's copyreturn $pence;}$base = 2750;echo withHolidaySurcharge($base), "\n"; // 3025echo withHolidaySurcharge($base), "\n"; // 3025: same answer againecho $base, "\n"; // 2750: unchanged
Pass by reference: an & before the parameter, function applyHolidaySurcharge(array &$booking), passes the argument by reference. The parameter becomes another name for the caller's variable (Act 03), so every change inside the function happens to the caller's variable. The argument must then be a variable: calling f(&$x)-style functions with a literal like f(5) throws an Error, "could not be passed by reference".
<?phpfunction addOne(int &$count): void{$count++;}$bookings = 4;addOne($bookings);echo $bookings, "\n"; // 5: the caller's variable changedtry {addOne(4);} catch (Error $e) {echo $e->getMessage(), "\n"; // addOne(): Argument #1 ($count) could not be passed by reference}
Why the surcharge was added twice: the preview called the helper to show a price, but because of the &, it changed $booking["pence"] from 2750 to 3025 for real. "Pay" then called it again on the changed booking and added 10% of 3025 on top. A function that changes its input in place does its work again on every call; one that returns a new value gives the same answer every time. The fix is to drop the & and return: $price = withHolidaySurcharge($booking["pence"]);. The booking stays as it was, and each screen calculates its own figure from it. And the reason the & was added — "so it doesn't copy" — was never true: thanks to copy-on-write, passing by value is just as fast.
<?phpdeclare(strict_types=1);function applyHolidaySurcharge(array &$booking): int{$booking["pence"] += intdiv($booking["pence"] * 10, 100); // changes the caller's booking!return $booking["pence"];}$booking = ["customer" => "Daniel Brooks", "pence" => 2750];echo "Preview: ", applyHolidaySurcharge($booking), "\n"; // Preview: 3025echo "Charged: ", applyHolidaySurcharge($booking), "\n"; // Charged: 3327 — added twice
<?phpdeclare(strict_types=1);function withHolidaySurcharge(int $pence): int{return $pence + intdiv($pence * 10, 100);}$booking = ["customer" => "Daniel Brooks", "pence" => 2750];echo "Preview: ", withHolidaySurcharge($booking["pence"]), "\n"; // Preview: 3025echo "Charged: ", withHolidaySurcharge($booking["pence"]), "\n"; // Charged: 3025echo "Stored: ", $booking["pence"], "\n"; // Stored: 2750
When references are right: some of PHP's own functions take references because they change their argument by design: all the sort functions, array_push(), array_splice(), shuffle(), and preg_match(), which fills its $matches parameter. That's a convention from older PHP, where returning several values was awkward. In your own code, prefer returning values — an array if there are several (chapter 1). Objects are different again: a function receives a handle to the same object, so it can change it without &; Act 11 explains why. The table below compares the two ways.
| Question | By value: f(array $booking) | By reference: f(array &$booking) |
|---|---|---|
| Can the function change the caller's variable? | No, it works on a copy | Yes, every change sticks |
| Calling it twice | Same answer each time | Changes the variable again |
| Can you pass a literal like 2750? | Yes | No: an Error |
| Cost of a big array | Cheap: copy-on-write | Cheap, but no faster |
| Use it for | Almost everything | Built-ins like sort(), preg_match(); rarely your own |
<?php$times = ["10:00", "9:00"];sort($times, SORT_NATURAL); // sorts $times itselfecho implode(" ", $times), "\n"; // 9:00 10:00if (preg_match('/^(\d+):(\d+)$/', "9:30", $matches)) { // fills $matchesecho $matches[1], " hours, ", $matches[2], " minutes\n"; // 9 hours, 30 minutes}
Key Takeaway
PHP passes arguments by value: the function gets a copy, so it can't change the caller's variable — and thanks to copy-on-write that costs nothing. An & before a parameter passes by reference: the function changes the caller's variable itself, again on every call. Use references only where a built-in requires them; in your own functions, return the new value instead.
Why This Matters
A function that quietly changes its input is a trap for whoever calls it next — here, a preview that changed the price it was only supposed to show. Passing by value and returning a new value means you can call a function as often as you like, in any order, and get the same answer.
Knowing which built-ins take references explains code you'll read every day: why sort($times) returns true, and where $matches comes from after preg_match().
The helper is now withHolidaySurcharge(int $pence): int, and Daniel is refunded £3.02. Mia moves the 10% rate into a variable at the top of the price file, $surchargeRate = 10;, so it's easy to change. The next holiday booking gets no surcharge at all — and a warning about an undefined variable. That's the next chapter: function scope.
