Sorting out PHP variable memory allocation problems

Source: Internet
Author: User
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.

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: info-contact@alibabacloud.com 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.