If I deep clone an object that contains another object while I have a reference in a variable of the inner property, the clone will not be deep.
<?php
class Person
{
public function __construct(
public string $name,
) {
}
}
class Country
{
public function __construct(
public Person $person,
) {
}
public function __clone()
{
$this->person = clone $this->person;
}
}
$usa = new Country(new Person('Arthur'));
$blah = &$usa->person;
$italy = clone $usa;
$italy->person->name = 'jack';
var_dump($usa);
var_dump($italy);
This line cause $usa
and $italy
to contain the same Person
property. Doing unset $blah
before cloning $usa works, but why ?
$blah = &$usa->person;
Outputs :
object(Country)#1 (1) {
["person"]=>
&object(Person)#4 (1) {
["name"]=>
string(4) "jack"
}
}
object(Country)#3 (1) {
["person"]=>
&object(Person)#4 (1) {
["name"]=>
string(4) "jack"
}
}