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 :()

4
  • 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 Commented Jun 27, 2023 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. Commented Jun 27, 2023 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```` Commented Jun 27, 2023 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 Commented Jun 27, 2023 at 16:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.