Zend PHP 7 Certification – Functions – References

This post covers the References section of the Functions chapter when studying for the Zend PHP 7 Certification.

You can pass a variable by reference to a function so the function can modify the variable.

<?php
function foo(&$var) {
    $var++;
}

$a = 5;
foo($a);
echo $a; // Outputs: 6

This is the correct way to pass by reference, and you don’t need to add & within the function call. Only the definition needs the ampersand. Attempting to add & within the function call is known as ‘call-time pass-by-reference’.

As of PHP 5.3.0, you will get a warning saying that ‘call-time pass-by-reference” is deprecated, and as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

It’s worth noting that if you use unset() to unset a variable in the function when passing by reference, the reference will be destroyed.

<?php
$x = 'x';
foo($x);
echo $x; // Outputs "x" and not "q23"

function foo(&$x) {
    unset( $x );
    $x = 'q23';
    return true;
}

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound.

To return references, you should use the ampersand, & on the function declaration, and to indicate that reference binding should be done on $value, seen below.

<?php
class Foo {
    public $value = 123;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new Foo();
$value = &$obj->getValue(); // $value is a reference to $obj->value, which is 123.
$obj->value = 45;
echo $value; // Outputs: 45

Here, the property of the object returned by the getValue function would be set, and not the copy as it would be without using reference syntax.

View the other sections:

Note: This article is based on PHP version 7.1.