QA
Beginner LevelPHP 8+

How do function arguments pass by value versus pass by reference (&$param) in PHP?

❓ Interview Prompt: Explain argument passing by value (Copy-on-Write) vs passing by reference with ampersand (&$param).

PHP functions support two ways of receiving parameter arguments:

1. Pass-by-Value (Default):

•
When a variable is passed to a function, PHP passes a copy of the value (optimized internally via Copy-on-Write).
•
Modifying the parameter inside the function does NOT alter the original variable outside the function.

2. Pass-by-Reference ('&$param'):

•
Prefixing a parameter with an ampersand ('&$param') passes the memory address reference of the original variable.
•
Any modification inside the function directly mutates the original variable in the calling scope!

Code Implementation Example

php
<?php
$count = 10;

// 1. Pass-by-Value
function incrementVal(int $val): void {
    $val++;
}
incrementVal($count);
echo $count; // Outputs 10 (unchanged!)

// 2. Pass-by-Reference (ampersand &$val)
function incrementRef(int &$val): void {
    $val++;
}
incrementRef($count);
echo $count; // Outputs 11 (original variable mutated!)
💡Comparing pass-by-value vs pass-by-reference argument mutation.
🎯 Interview Key Takeaway

Function parameters pass by value by default. Use ampersand (&$param) to pass by reference and mutate original variables.

#Functions#Pass-by-Reference#Parameters#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?