W3docs

How to Pass Variables by Reference in PHP

Working with variables is an essential part of a developer’s life. In this snippet, we will demonstrate to you how to pass variables by reference with PHP.

PHP variables, but not objects, are passed by value by default. When passed by value, a copy of the variable is created inside the function. Modifications to the copy do not affect the original variable.

Let’s see an example:

php assign a new value to string variable

<?php

// Function used for assigning new
// value to $string variable and
// printing it
function print_string($string)
{
  $string = "W3docs" . "\n";

  // Print $string variable
  print $string;
}

// Driver code
$string = "Global w3docs" . "\n";
print_string($string);
print $string;

?>

php assign a new value to string variable output

W3docs
Global w3docs

Pass by Reference

To pass a variable by reference, add the ampersand (<kbd class="highlighted">&</kbd>) symbol to the function parameter. An example of such a function definition looks as follows: <kbd class="highlighted">function( &$x )</kbd>.

Instead of creating a copy, the function parameter now points to the same memory address as the original variable. Consequently, modifying the variable inside the function directly changes the original variable.

Here is a clear example:

php pass variable by reference

<?php

// Function applied to assign a new value to
// $string variable and printing it
function print_string(&$string)
{
  $string = "Function w3docs \n";

  // Print $string variable
  print $string;
}

// Driver code
$string = "Global w3docs \n";
print_string($string);
print $string;

?>

php pass variable by reference output

Function w3docs 
Function w3docs

PHP Objects

In PHP, objects are passed by reference by default.

Example of a PHP object

<?php

class SimpleClass {
    public int $x = 0;
}

function changeClassProperty(SimpleClass $object): void
{
    $object->x = 1;
}

// create an instance of the class
$instance = new SimpleClass();

// make sure that objects are being passed with the reference by default
changeClassProperty($instance);

echo $instance->x;

?>
1

Defining Variables in PHP

As a rule, PHP variables start with the <kbd class="highlighted">$</kbd> sign followed by the variable name.

While assigning a text value to a variable, putting quotes around the value is necessary.

In contrast to other programming languages, PHP doesn’t have a command to declare a variable. It is generated at the moment a value is first assigned to it.

In PHP, variables are containers to store data.

The PHP variables may have both short( for instance, x and y) and more descriptive names (fruitname, age, height, and so on).