user1581029
user1581029

Reputation: 61

Variable reference in php

The output of this PHP code is 33.

$b=2;
$a=&$b;
$a=3;
print $a;
print $b;

How did $b become 3?

Upvotes: 3

Views: 144

Answers (5)

Tarun
Tarun

Reputation: 3165

References in php

As you can see from the above image , when you assign a reference of a variable to another variable then they both point to same location ,thus changes made by one reflect to other as well.
Thanks

Upvotes: 3

rationalboss
rationalboss

Reputation: 5389

$a=&$b; this line is like saying "from now on $b, you are also $a."

print $a; // prints 3
print $b; // prints another 3

Upvotes: 1

JNF
JNF

Reputation: 3730

Once you make a reference $a and $b are two names for the same variable.

See also: http://php.net/manual/en/language.references.php (Specifically first article in the list)

Upvotes: 1

GautamD31
GautamD31

Reputation: 28763

You are sotring the "$b's address into the $a,and after that $a is changed,so that the value in the $b's address have changed and thus $b also changed

Upvotes: 1

Vinayak Phal
Vinayak Phal

Reputation: 8919

As $a is pointing to the $b memory location.

Now if you change value of $a it will actually update $b value (where the $b is stored). As both are pointing to the same memory location.

OR you can say $a and $b are the two different way to access the same memory location as you've assigned reference of $b to $a.

Upvotes: 4

Related Questions