Return-by-Reference in PHP

NOTE:

When a function definition is preceded by an ampersand it means this function uses Returning by reference.

The concept of return-by-reference is obscure—yet it is very prominent in CodeIgniter.

The way it is implemented is syntactically similar to pass-by-reference. The & is used in the type hinting when defining the function and in the assignment statement which assigns the return value to a variable. See example:

Note: Unlike parameter passing, here you have to use & in both places – to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

<?php
class foo {
    public $value = 42;

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

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;                // prints the new value of $obj->value, i.e. 2.
?>

Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference.

To use the returned reference, you must use reference assignment:

<?php
function &collector() {
  static $collection = array();
  return $collection;
}
$collection = &collector();
$collection[] = 'foo';
?>

To pass the returned reference to another function expecting a reference you can use this syntax:

<?php
function &collector() {
  static $collection = array();
  return $collection;
}
array_push(collector(), 'foo');
?>
Advertisements

About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in PHP Data Value Types, PHP Language Constructs. Bookmark the permalink.

One Response to Return-by-Reference in PHP

  1. Pingback: Common.php CI Explained | Sam's PHP

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s