Today I came across a question about the memory allocation of PHP variables, recorded.
The following code:
Copy Code code 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 it output, the result is one, $b = $a when there is no new allocation of memory, AB is pointing to the same area, $b [' Child ']= $a, the $b will copy a copy of the original $a content, and then modify, which means $b and $a point to different areas, and then modify the $ A or $b will not affect each other.
Look at this code again:
Copy Code code 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 output, the result is 22, according to the actual situation to judge, $b->child= $a, and did not like the array, copy a copy, AB and A->child are pointing to the same area, so change any one, the others will be changed.
But why is PHP designed to do this?