PHP variable memory allocation problem record collation

  • 2020-11-20 06:02:37
  • OfStack

Today I encountered a problem about the memory allocation of the php variable, record 1.

Here's the code:
 
$a = array ( 
'str' => 1, 
'child' => 2 
); 

$b = $a; 
$b['child'] = $a; 
$b['child']['str'] = 2; 
echo $b['str']; 
$b = null; 
echo $a['str']; 

When $b=$a, there is no new memory allocated. When $b['child']=$a, $b points to the same region. When $b['child']=$a, $b points to the original $a first, and then changes it.

Look at this code again:
 
class A 
{ 
public $str = ''; 
public $child; 
} 

$a = new A(); 
$b = $a; 
$a->str = 1; 
$a->child = 2; 
$b->child = $a; 
$b->child->str = 2; 
echo $b->str; 
$b = null; 
echo $a->str; 

So what's going to be the output? It's going to be 22, depending on what's going on, $b- > When child=$a, copy1, ab, and a- are not rewritten as arrays > child is all pointing to the same area, so if you change any one of them, the others will change.

But why is the PHP designed this way?

Related articles: