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,
and
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
Posted: Thu Nov 24, 2005 10:43 am
by Weirdan
In simple english:
after executing
$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
$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!
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!
Bez problem
[Moderator's hat on]
However we speak English here
[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
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!