Today I encountered a problem about memory allocation of PHP variables. I will record it.
The following code:
Copy code The code is as follows:
$a = array (
'str' => 1,
'child' => 2
);
$b = $a;
$b['child'] = $a;
$b['child']['str'] = 2;
echo $b['str'];
$b = null;
echo $a['str'];
What will be output? The result is 11. When $b=$a, there is no new memory allocated. ab points to the same area, $b['child']=$a , $b will first copy the original content of $a, and then modify it. That is to say, $b and $a point to different areas at this time, and they will not affect each other when modifying $a or $b. .
Look at this code again:
Copy the code The code is as follows:
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;
What will be output? The result is 22, depending on the actual situation It is judged that when $b->child=$a, there is no new copy like the array. Both ab and a->child point to the same area. If any one is changed in this way, the rest will be Change it.
But why is PHP designed like this?
http://www.bkjia.com/PHPjc/621711.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621711.htmlTechArticleToday I encountered a problem about php variable memory allocation, record it. This code is as follows: Copy the code as follows: $a = array ( 'str' = 1, 'child' = 2 ); $b = $a; $b['child']...