Today, I encountered a php variable memory allocation problem. let's record it below. Don't miss out on a problem about php variable memory allocation today. let's record it.
The following code is used:
The code is as follows:
$ A = array (
'Str' => 1,
'Child '=> 2
);
$ B = $;
$ B ['child '] = $;
$ B ['child '] ['str'] = 2;
Echo $ B ['str'];
$ B = null;
Echo $ a ['str'];
What will be output? the result is 11. when $ B = $ a, no memory is actually allocated, and AB is directed to the same region, $ B ['child '] = $ a, $ B will first copy the original $ a content and then modify it, that is to say, $ B and $ a point to different regions at this time, and then change $ a or $ B will not affect each other.
Let's look at this code again:
The code is as follows:
Class
{
Public $ str = '';
Public $ child;
}
$ A = new ();
$ B = $;
$ A-> str = 1;
$ A-> child = 2;
$ B-> child = $;
$ B-> child-> str = 2;
Echo $ B-> str;
$ B = null;
Echo $ a-> str;
What will be output? the result is 22, which is determined based on the actual situation. when $ B-> child = $ a, there is no copy as an array, both AB and a-> child point to the same area. in this way, the other parts will be changed.
But why is PHP designed like this.