The program first creates a $ a variable, and then assigns the variable $ a as 'helloworld '. create a $ B variable and assign the $ a variable to the $ B variable. here, we need to think about how the program creates a $ a variable and then assigns the $ a variable 'helloworld '. create a $ B variable and assign the $ a variable to the $ B variable. here we need to think about the current memory situation. if the memory usage of $ a variable is 22 bytes (assuming value), how many bytes does $ B occupy? 22 bytes? Or less than 22 bytes? The answer is less than 22 bytes. how is PHP implemented?
In fact, PHP is implemented through refcount. when a variable is assigned to another variable, PHP simply adds the value of the variable refcount to 1. the zend_hash_add function and ZVAL_ADDREF macro are used. for details, refer to the following code:
[Php]
{
Zval * helloval;
MAKE_STD_ZVAL (helloval );
ZVAL_STRING (helloval, "HelloWorld", 1 );
Zend_hash_add (EG (active_symbol_table), "a", sizeof ("a"), & helloval, sizeof (zval *), NULL );
ZVAL_ADDREF (helloval );
Zend_hash_add (EG (active_symbol_table), "B", sizeof ("B"), & helloval, sizeof (zval *), NULL );
} [/Php]
From the code above, we can see that the variable is not added, and it is still a variable of helloval. however, we can also see that the reference counter is added through the ZVAL_ADDREF macro. so helloval-> refcount ++. in addition, a symbol named B is added to the activity symbol table through zend_hash_add. therefore, we can minimize the memory usage.
We can verify the code by using the PHP built-in function memory_get_usage:
[Php]
$ M1 = memory_get_usage ();
$ A = 1;
$ M2 = memory_get_usage ();
$ B = $;
$ M3 = memory_get_usage ();
Echo $ m2-$ m1 ,"
", $ M3-$ m2;
?> [/Php]
The experiment proves that we are right!
So when can $ B become a real variable? We can assign a new value to $ B:
[Php]
$ A = 1;
$ B = $;
$ B = 2;
?> [/Php]
In this way, you can allocate new space in the memory!
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