If a variable is passed by value (as in example1 below), then any changes made to that variable within the function are purely within the scope of the function. Effectively, a copy is created by the function call, which can be modified.... but because it's a copy the original variable in the calling code won't be changed, and the copy will be removed when the function terminates.
If a variable is passed by reference (as in example2 below), then any changes made to that variable within the function will change that value in the calling code as well.
Code: Select all
$dataVal = 1;
function example1($var) {
$var++;
echo 'Increment var in function 1 = '.$var.'<br />';
}
function example2(&$var) {
$var++;
echo 'Increment var in function 2: '.$var.'<br />';
}
echo 'Initial value of $dataVal is: '.$dataVal.'<br />';
example1($dataVal);
echo 'Current value of $dataVal is: '.$dataVal.'<br />';
example2($dataVal);
echo 'Current value of $dataVal is: '.$dataVal.'<br />';
should give:
Code: Select all
Initial value of $dataVal is: 1
Increment var in function 1 = 2
Current value of $dataVal is: 1
Increment var in function 2 = 2
Current value of $dataVal is: 2