Today, I encountered a php variable memory allocation problem. Let's record it.
The following code is used:
Copy codeThe 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:
Copy codeThe 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.