Page 1 of 1
Help with variable operators
Posted: Fri May 22, 2009 5:12 am
by ben.artiss
Hi everyone,
I've seen these kinds of 'operators' (not sure if that's the right word!) used in Joomla and was just wondering if I have the right impression of what they're for.
Code: Select all
$var =& $class->function();
# or
function example(&$var,$val) {...}
It looks to me like it's an equivalent to @, which stops PHP from outputting errors - is that right? So if the variable is not defined it won't show you an error?
Thanks, Ben
Re: Help with variable operators
Posted: Fri May 22, 2009 7:53 am
by Gabriel
Not quite.
A variable with an ampersand at its definition assigns the
variable by reference. So more or less, the new variable points to the old one, rather than copying it.
Re: Help with variable operators
Posted: Fri May 22, 2009 10:57 am
by Mark Baker
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