What is the difference between mutable variables and reference assignment in php?

怪我咯
Release: 2023-03-10 21:00:01
Original
1232 people have browsed it

Let me explain it to you from the perspective of the PHP kernel. You can fully understand it if you understand it deeply;
PHP variables are all passed in the kernel through C languageThe structure zval is stored (if you have not learned C, you can understand it as an object, and the member variables inside are all attributes of the class. For the time being, understand it this way). The zval structure is as follows:

struct _zval_struct {
zvalue_value value; // 存储变量的值
zend_uint refcountgc; //表示引用计数 默认为:1
zend_uchar type; // 变量具体的类型
zend_uchar is_refgc; //表示是否为引用
};
Copy after login

For example, php code is as follows:

$a = 10;
$b = $a;
Copy after login

At this time, $b has no reference, but only assigns the value of $a to $b, then zval is The refcountgc in the structure becomes 2, and is_refgc is still false, indicating that it is not referenced, because the kernel $a has opened up a memory space. When $a is assigned to $b, the value of $b only points to $a, so This eliminates the need to re-open a piece of memory, but when the value of $b is changed (the value of $a will not change), $b will open up a new memory space. This is the so-called copy-on-write, How PHP variables are stored in the kernel, let’s talk about the references below:

$a = 10;
$b = &$a;
Copy after login

At this time, the structure that stores $a in the kernel is_refgc is marked as true, which means it is a reference, then $ Both a and $b point to the same memory address. When $b=20, $a will also become 20

The above is the detailed content of What is the difference between mutable variables and reference assignment in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!