PHP changes the type of $ a from integer to object. What for?

<?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
?>

Conclusion:

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
+3
source share
6 answers

This is because you set $ b to share the same memory address as $ a. Therefore, when you change $ b, the value of $ a also changes.

Set $b = $ainstead $b = &$aif the results are undesirable.

+3
source
  • $bis reference up to $a.
  • You make $bequal $cto the object.
  • This means that $bit is now an object ...
  • ... and since $b- it's just a reference to $a, $aalso an object.
+3
source

$b $a:

$b = &$a;

$b , $c:

$b = $c;

$b $a , , $a .

stdClass: $c, . $c, $b, . $b $a ( ).

+1

php , : http://php.net/manual/en/language.references.php

a ( - Tomalak) b, &, , b a, , , b=c ( c ), b , a ( b) .

0

$b = &$a $a, $b $a - , .

0

:

$b = &$a; 

When you assign an object $b, it is inherited $a. The destination does not overwrite the link. Instead of $ b, it is a nickname for $ a content, so all the changes you apply to $ b will actually appear in $ a instead. $ b only saves the link, not the properties.

0
source

All Articles