PHP References
What is reference
A reference is a method to accesses same variable contents with other names or just like other variable.
It’s functionality looks like pointer but It’s not like C(C programming language) pointer. C language performs this type functionality via pointer and C pointer uses actual memory address to denote reference.
PHP variables and it’s content are different to each other. So there are any same content have different names {$variable}.
References syntax
There are reference uses & symbol to perform it’s own operations of references.
<?php
$x =& $y;
?>
Output:
What references do
PHP references performs three basic operations, These are given here:
-
Assign By Reference
-
Pass By Reference
-
Return By Reference
Assign By Reference
In this two variables named $x and $y have been refers to same content is [CONTENT].
There are $x and $y are completely equal to each other in variable’s value.
It does not points to each other, but These both variables points to content [CONTENT] or same place.
Understand references with an example:
<?php
function foo(&$var) { }
foo($a); // $a is "created" and assigned to null
$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)
$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>
Pass By Reference
The second thing references do is to pass variables by reference.
This is done by making a local variable in a function and a variable in the calling scope referencing the same content.
Example:
<?php
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
?>
Return By Reference
Returning by reference is useful when you want to use a function to find to which variable a reference should be bound.
Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own.
Example:
<?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:
Note:
How to unset a reference
<?php
$x = 1;
$y =& $x;
unset($x);
?>
won't unset $y, just $x.