⊗ppOpAdPBR 23 of 107 menu

Passing Objects by Reference in OOP in PHP

Suppose we have the following class User:

<?php class User { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } ?>

Suppose we create an object of this class:

<?php $user = new User('john', 30); ?>

Now imagine the following situation: you want to assign the value of the variable $user to some other variable, for example $test.

If we were talking not about objects, but about primitives, such as strings, numbers, arrays, etc., then the variable $test would receive a copy of the value of the variable $user.

This means that changes to either variable in the future would not change the value of the other variable. Let's look at an example:

<?php $user = 1; $test = $user; // the variable $test now has 1 $test = 2; // the variable $test now has 2, and $user still has 1 ?>

With objects, it's different - when assigned to another variable, objects are not copied, but are passed by reference: this means that both of these variables have as their value the same object. This has an important consequence: if you change any properties of the object using one variable, the same changes will appear in the second variable.

Let's see it in practice. Let's create a user object:

<?php $user = new User('john', 30); ?>

Let's assign the object to another variable:

<?php $test = $user; ?>

Let's change the name property in the variable $test

<?php $test->name = 'eric'; ?>

Let's check that the shared object has changed. Let's output the name property from the variable $user:

<?php echo $user->name; // will output 'eric'! ?>

Create a class Product, in which there will be the following properties: name, price.

Create an object of the class Product, write it to the variable $product1.

Assign the value of the variable $product1 to the variable $product2. Check that both variables reference the same object.

byenru