How To Reference A PHP Variable

How To Reference A PHP Variable
This tutorial will show you how to allow a function to change a variable that is not part of the function.

As you learned in past tutorials, when you pass the value of a variable to a function you use an argument such as function_name($argument). This creates a "local copy" of the original variable which will be manipulated by the function. Any change to the local copy of the variable within the function does not affect the value of the original (outside) variable. But, there are times when you want to use the function to change the value of the original (outside) variable; not just the value of the copy. How would you do this?

You can reference, or point to, the original variable when you pass an argument to the function. By doing this, you can manipulate the value of the original (outside) variable from within the function. Let's take a look at a sample code.

function multi_by_3(&$number)
{ $number *= 3; }
$start_no = 2;
multi_by_3($start_no);
echo $start_no;

function multi_by_3(&$number)
function function_name(&$argument)
As you can see, this is your basic function code with one exception. The difference is the ampersand (&) in front of the argument ($number) and this points to (reference) the outside variable $start_no. At the beginning of the function, the value of the $start_no variable is 2.

{ $number *= 3; }
{ body of function }
This line of code multiplies the $number variable by 3. At this point, the original value of the $start_no variable (2) has been changed to 6.

$start_no = 2;
$variable = value;
This sets the initial value of the $start_no variable to 2. This is a value of the outside variable at the time of the function call.

multi_by_3($start_no);
function_name( );
This is the function call.

echo $start_no;
Because it follows the function call, this echo statement will print the new value of the $start_no variable to the browser. The new value is 6.






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.