Reference in PHP

 
/**
 * In PHP variables are passed by value (not by reference).
 * A reference allows two different variable names to point to the same memory location.
 */

$a = 10; 
$b = &$a; // $b references $a 

$b = 20;
echo $a; // 20

$a = 30;
echo $b;  // 30

Functions

 
/**
 * By default, function arguments in PHP are passed by value (copied).
 * If you want a function to modify the value, you pass it by reference.
 * 
 * This is recommended only for large datasets.
 * In pure functional programming, passing by reference is not recommended.
 */

function addUser(&$users, $user): void
{
    $users[] = $user;
}

$team = ["Alice", "Bob"];
addUser($team, "John");
addUser($team, "Mary");

print_r($team);  // Alice, Bob, John, Mary

Array

 
/**
 * Reference with foreach changes the array (use it with care).
 */

$A = [1, 2, 3, 4];

foreach ($A as &$val) { // Look Here
    $val *= 2;
}

print_r($A);  // [2, 4, 6, 8]

Object

 
/**
 * In PHP objects are passed by value, just like scalars and arrays.
 * But the "value" of an object variable is a handle (an identifier).
 * This gives them reference-like behavior when modifying properties.
 * 
 */

class MyClass 
{
    public $value = 1;
}

function modify($obj): void
{
    $obj->value = 2;  // modifies the underlying object
}

$a = new MyClass();
modify($a);
echo $a->value;  // 2






Questions and answers:
Clink on Option to Answer




1. How are variables passed in PHP?

  • a) by value (copy)
  • b) by reference

2. How are objects passed in PHP?

  • a) by value
  • b) by reference

3. How are objects properties passed?

  • a) by value
  • b) by reference

4. How are function arguments passed?

  • a) by value (copy)
  • b) by reference


References: