References in PHP

Introduction

In this article I will explain references in PHP. References are not pointers. In PHP references are a way to access the same variable content using a different name. PHP reference are not like C pointers,
for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses. There are three basic operations performed using references, such as assigning by reference, passing by reference, and returning by reference. and so on. 

Example

<?php

 $foo = 'Hello';

 $bar = 'World';

 echo $foo."<br>";

 echo $bar;

?>

Output

references2.jpg

references1.jpg

<?php

 $bar = & $foo;

?>

references3.jpg

Returning References

The following is an example of passing arguments to a function by reference:

Example

<?php

function inc(& $b) {

 $b++;

}

$a = 1;

inc($a);

echo $a;

?>

Output

references5.jpg

References are not pointers. In other words, the following constructs what you expect (a function may return a reference to data as opposed to a copy):

<?php

function & get_data() {

 $data = "Hello World";

 return $data;

}

$foo = & get_data();

?>

Example

The following is an example of using references with undefined variables:

<?php

function foo(&$var)

{ }

foo($a);

$b = array();

foo($b['b']);

var_dump(array_key_exists('b', $b));

$c = new StdClass;

foo($c->d);

var_dump(property_exists($c, 'd'));

?>

Output

 references4.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all