PHP variable memory allocation problem record sorting_PHP tutorial

WBOY
Release: 2016-07-13 17:17:47
Original
862 people have browsed it

Today I encountered a problem about memory allocation of PHP variables. I will record it.

The following code:

Copy code The code is 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 be output? The result is 11. When $b=$a, there is no new memory allocated. ab points to the same area, $b['child']=$a , $b will first copy the original content of $a, and then modify it. That is to say, $b and $a point to different areas at this time, and they will not affect each other when modifying $a or $b. .

Look at this code again:
Copy the code The code is 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 be output? The result is 22, depending on the actual situation It is judged that when $b->child=$a, there is no new copy like the array. Both ab and a->child point to the same area. If any one is changed in this way, the rest will be Change it.

But why is PHP designed like this?

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621711.htmlTechArticleToday I encountered a problem about php variable memory allocation, record it. This code is as follows: Copy the code as follows: $a = array ( 'str' = 1, 'child' = 2 ); $b = $a; $b['child']...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!