3

The values that are printed are both 11 and 12. Why is this? And is there a way to remove the reference for the clone?

class A {
    public $z = 10;
}

$a1 = new A();

$z = &$a1->z;

$a2 = clone $a1;

$a1->z = 11;

var_dump($z);

$a2->z = 12;

var_dump($z);
user2180613
  • 739
  • 6
  • 21

1 Answers1

0

Why is this?

A: When you are cloning you are also cloning the reference.

$z = &Ref to $a1->z [0x000F]

$a2-z = [0x000F]

$a1->z = 11; //[0x000F] = 11;

Since both class instances reference the same memory, when you change $z it changes the value of both classes.

The only way to derefernce that value would be to unset it.

unset($a2->z);
$a2->z = 12;

here's a full example.

class A {
    public $z = 10;
}

$a1 = new A();

$z = &$a1->z;

$a2 = clone $a1;

$a3 = clone $a2;

$a1->z = 11;

var_dump($z);

$a2->z = 12;

var_dump($z);

unset($a3->z);
$a3->z = 13;
var_dump($z);
var_dump($a3->z);

The output is

int(11)
int(12)
int(12) //$z
int(13) //$a3->z So $a3->z is now unlinked from the Unset

I hope this answers your question

geggleto
  • 2,605
  • 1
  • 15
  • 18