How to Pass Variables by Reference in PHP

PHP variables, but not objects, by default, are passed by value. Once PHP variables are passed by value, the variable scope, defined at the function level is linked within the scope of the function. Modification of either of the variables has no impact.

Let’s see an example:

<?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;

?>

The output will look as follows:

  Function w3docs
  Global w3docs

Pass by Reference

For passing variables by reference, it is necessary to add the ampersand (&) symbol before the argument of the variable.

An example of such a function will look as follows: function( &$x ).

The scope of the global and function variables becomes global. The reason is that they are defined by the same reference. Hence, after changing the global variable, the variable that is inside the function also gets changed.

Here is a clear example:

<?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;

?>

The output will be:

  Function w3docs 
  Function w3docs

PHP Objects

PHP Objects by default are being passed by reference.
<?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;

?>

The output will look as follows:

1

Defining Variables in PHP

As a rule, PHP variables start with the $ 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).