-1

I'm learning the basics concept of php. Here is the code of referencing variable. Could someone explain it for me.

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$car = &$bar;

$bar = "My name is $bar";  // Alter $bar...

echo $bar ."\n\n";
echo $foo ."\n\n";                 // $foo, $car are altered too.
echo $car ."\n\n";                 // $foo, $car are altered too.
//My name is bob
//My name is bob
//My name is bob
?>
Jestin
  • 578
  • 5
  • 10

1 Answers1

0

Try this..

You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:

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

$a=5;
foo($a);
// $a is 6 here
?>

Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

Pass by Reference

References allow two variables to refer to the same content. In other words, a variable points to its content (rather than becoming that content). Passing by reference allows two variables to point to the same content under different names. The ampersand ( & ) is placed before the variable to be referenced.

$a = 1;
$b = &$a; // $b references the same value as $a, currently 1
$b = $b + 1; // 1 is added to $b, which effects $a the same way
echo "b is equal to $b, and a is equal to $a";

Output:

b is equal to 2, and a is equal to 2

Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.

function add(&$var){ // The &amp; is before the argument $var
$var++;
}
$a = 1;
$b = 10;
add($a);
echo "a is $a,";
add($b);
echo " a is $a, and b is $b"; //

Output:

a is 2, a is 2, and b is 11

You can also do this to alter an array with foreach:

$array = array(1,2,3,4);
foreach ($array as &$value){
$value = $value + 10;
}
unset ($value); // Must be included, $value remains after foreach loop
print_r($array);

**Output:**

Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 )

Ref:http://php.net/manual/en/language.references.pass.php

http://www.phpreferencebook.com/samples/php-pass-by-reference/

Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50