Sobes.tech
Junior — Middle

Can you list different types of references used in PHP?

sobes.tech AI

Answer from AI

In PHP, the following types of references exist:

  1. Variable references — allow creating aliases for variables. Changes through the reference are reflected on the original variable.
$a = 5;
$b = &$a; // $b is a reference to $a
$b = 10;
echo $a; // will output 10
  1. References in functions (pass by reference) — allow functions to modify the passed arguments.
function increment(&$num) {
    $num++;
}

$value = 1;
increment($value);
echo $value; // will output 2
  1. References to objects — starting from PHP 5, objects are passed by reference by default, meaning that when assigning an object to a variable, both variables refer to the same object.
class MyClass {
    public $prop = 1;
}
$obj1 = new MyClass();
$obj2 = $obj1;
$obj2->prop = 2;
echo $obj1->prop; // will output 2

Thus, references in PHP allow working with data more efficiently, avoiding copying and enabling data modification in different parts of the code.