Page 1 of 1

References

Posted: Thu Nov 24, 2005 10:37 am
by evilmonkey
Hello,

Can someone please explain to me (preferably in simple English) what references are? I looked at the PHP manual, but I don't understand a thing. I am especially interested in the "&" symbol and what it allows me to do. From what I can see,

Code: Select all

$x=5;
$y = $x;
and

Code: Select all

$x=5;
$y =& $x;
produces identical results...

Thanks!

Posted: Thu Nov 24, 2005 10:40 am
by Weirdan
consider this:

Code: Select all

$x = 5;
$y = $x;
var_dump($x, $y);
$y = 15;
var_dump($x, $y);
and this:

Code: Select all

$x = 5;
$y =& $x;
var_dump($x, $y);
$y = 15;
var_dump($x, $y);

Posted: Thu Nov 24, 2005 10:42 am
by neophyte
Read the complete scoop on the & sign here:

http://us3.php.net/manual/en/language.r ... es.whatare

Posted: Thu Nov 24, 2005 10:43 am
by Weirdan
In simple english:
after executing

Code: Select all

$y =& $x;
$y is an alias for $x. Any further changes to $y would be reflected to $x as well

Posted: Thu Nov 24, 2005 10:45 am
by evilmonkey
Weirdan wrote:In simple english:
after executing

Code: Select all

$y =& $x;
$y is an alias for $x. Any further changes to $y would be reflected to $x as well
Yes, that is exactly the explanation I needed. I was considering putting "in simple English or Russian", but decided not to, didn't realize there were people who spoke Russian here. Spasibo! :D

Oh, one more thing. Are changes to $x reflected on $y?

Posted: Thu Nov 24, 2005 10:58 am
by Weirdan
evilmonkey wrote: Yes, that is exactly the explanation I needed. I was considering putting "in simple English or Russian", but decided not to, didn't realize there were people who spoke Russian here. Spasibo! :D
Bez problem :P
[Moderator's hat on]
However we speak English here :twisted:
[Moderator's hat off]
evilmonkey wrote: Oh, one more thing. Are changes to $x reflected on $y?
Yes, they are. In fact when $y is a reference to $x you could use both interchangeably.

Posted: Thu Nov 24, 2005 10:58 am
by neophyte
And an amerpsand in a function parameter like:

Code: Select all

$somevar = 5;
    function foobar($somevar){
        //this is called passing by reference
        //What ever you do to $somevar in the function is reflected outside the function
        $somevar = 12;
   }
    foobar(&$somevar);
   echo $somevar;  //outputs 12

Posted: Thu Nov 24, 2005 11:08 am
by Weirdan
neophyte wrote:

Code: Select all

foobar(&$somevar);
This syntax would cause warnings:
Warning wrote: PHP Warning: Call-time pass-by-reference has been deprecated - argument passed
by value

Posted: Thu Nov 24, 2005 11:29 am
by neophyte
Wouldn't you know it...

So correct would be:

Code: Select all

$somevar = 5;
function foobar(&$somevar){
   //function stuff
   
}

foobar($somevar);

Posted: Thu Nov 24, 2005 12:12 pm
by evilmonkey
Alright, that more or less clears things up. Thanks guys!