Help with variable operators

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ben.artiss
Forum Contributor
Posts: 116
Joined: Fri Jan 23, 2009 3:04 pm

Help with variable operators

Post 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
User avatar
Gabriel
Forum Commoner
Posts: 41
Joined: Wed May 06, 2009 8:12 pm
Location: Las Vegas

Re: Help with variable operators

Post 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.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Help with variable operators

Post 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
 
Post Reply