Sorting out PHP variable Memory Allocation Problems

Source: Internet
Author: User

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:
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.