0

I have a script php code

<?php
class A
{
    public $x;
}

$a = new A();
$a->x = 10;

$b = &$a;
$b = new A();
$b->x = 20;


echo $a->x;

When try to understand code I think the result is

10

But the result is: 20

I don't undersand what's going on!,

I also try with bing: enter image description here Hope someone can help me explain the code. Thank you :()

Tran Van Hieu
  • 11
  • 1
  • 1
  • 1
    You set the value here `$b->x = 20;` and as `$b` is a reference to `$a` because you used `&` in `$b = &$a;` you are setting `$a`'s value because they are now both the same object – RiggsFolly Jun 27 '23 at 16:22
  • 2
    When you assign an object to a new variable or create a reference to an object, it does not create a deep copy of the object. Instead, it creates a new reference to the same object in memory. So when you assigned `$b` to a new instance, it didn't create a separate object but instead changed the reference of `$b` to the new instance. Since both `$a` and `$b` were pointing to the same object, modifying the object through `$b` will also affect `$a`. – GrumpyCrouton Jun 27 '23 at 16:23
  • thank you for your answers but. Acctually I assign ```$b``` for new reference ```$b = new A();``` at this code maybe ```$b``` have not any ref to ```$a``` but I don't know why I change ```$b->x``` it also change ```$a```` – Tran Van Hieu Jun 27 '23 at 16:35
  • @TranVanHieu When you make `$b = &$a`, that means both `$a` and `$b` reference the same object in memory, so when you create a new instance using `$b = new A()`, _you are replacing the original instance of object `A`_, because ANY change to `$b` will also be made to `$a`, and vice versa, because they are _referencing the same object in memory_ – GrumpyCrouton Jun 27 '23 at 16:42

0 Answers0