PHP changes the type of $a from integer to object. Why?
<?php
$a = 3;
echo 'typeof $a is : ' . gettype($a) . "\n"; // integer
$b = &$a;
echo 'typeof $b es : ' . gettype($b) . "\n"; // integer
$c = new stdClass;
$c->name = "charles";
$b = $c;
$b->name = "bill";
echo '$c->name : ' . $c->name . "\n";
echo 'typeof $b es : ' . gettype($b) . "\n";
echo 'typeof $a is : ' . gettype($a) . "\n"; // object
echo 'The value of $a is : '开发者_运维百科 . $a->name; // bill
?>
Output:
typeof $a is : integer
typeof $b is : integer
$c->name : bill
typeof $b is : object
typeof $a is : object
The value of $a is : bill
It's because you're setting $b to share the same memory address as $a. So when you change $b, $a gets changed as well.
Set $b = $a
instead of $b = &$a
if the results are undesirable.
$b
is a reference to$a
.- You make
$b
equal to$c
, an object. - That means
$b
is now an object... - ...and since
$b
is just a reference to$a
,$a
is an object too.
You tell $b
to be a reference to $a
:
$b = &$a;
Then you tell $b
to refer to the object that is referred to by $c
:
$b = $c;
Since $b
and $a
are "linked" to the same value, both are the same reference to the same object, and $a
loses its integer value.
You now have two distinct references to a single stdClass
object: one belongs to $c
, which is obtained by creating the object and assigning it. The other is created by assigning the reference of $c
, by value to $b
, so it's copied. This is then shared by linking $b
and $a
together (assigning by reference).
Here is the php documentation on references, must read: http://php.net/manual/en/language.references.php
Because a
is a reference (not a copy - thanks Tomalak) of b
, because you use the &
, so whenever b
changes a
will change also. So when later on you make b=c
(which currently c
is an object) b
becomes an object and thus a
(the reference of b
) becomes one too.
Because $b = &$a
refer to $a
, so $b
and $a
are the same thing, and any references to either are interchangeable.
Your problem centers around creating this reference:
$b = &$a;
When you afterwards assign an object to $b
it will be inherited by $a
. The assignment does not overwrite the reference. Instead $b is a name alias for $a's content, so all changes that you apply to $b will actually show up in $a instead. $b only retains the reference, not the properties.
精彩评论