PHP variable memory allocation problem recording and finishing _php techniques

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

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.