[nycphp-talk] newbie confusion
Joseph Crawford
codebowl at gmail.com
Thu Nov 11 09:14:33 EST 2004
> I'm curious to know what the "&" is for in the statement below?
>
> -Aaron
Let me explain a bit and try to make it so you understand. In PHP &
is the reference operator, this allows you to pass a variable by
reference rather than by value. Here is an example
$var = 4;
func( $var );
// echo's 4
echo $var;
function func( $var ) {
$var++;
// echo's 5
echo $var;
}
if you run this code, you will see how the values of $var are
different inside the function and outside the function. The one
outside the function is 4 and the one inside is 4. When you pass by
value php defaults to making a copy of the variable.
When you use the & (reference operator) it will pass $var by reference
rather than by value, this passes the memory address rather than
making a copy of the variable. Let me show anoher example.
$var = 4;
func( &$var );
// echo's 5
echo $var;
function ( $var ) {
$var++;
}
If i am correct about this (which i believe i am) when you echo $var
after the function call, $var now equals 5 because you passed the
variable by reference rather than letting PHP make a copy. You need
to be careful passing variables/objects by reference, if you do not
intend to have the function change the value of the variable outside
of the functions scope, do not pass by reference.
I hope you understood everything i have said, if you do not, please
feel free to ask any questions reguarding my reply.
--
Joseph Crawford Jr.
Codebowl Solutions
codebowl at gmail.com
For a GMail account
contact me OFF-LIST
More information about the talk
mailing list