PHP object-oriented value passing method, php object-oriented
1 <? Php 2 // declare a variable and assign the value 3 $ a = 1; 4 // assign the value of the data type to a variable 5 $ B = $; 6 7 // modify the value of $ a 8 $ a = 2; 9 // $ a and $ B are two independent Memory Spaces. modify one of them but not the other 10 echo $ B; // 1 11 12 class Person13 {14 public $ name; 15 public $ age; 16} 17 // assign the object type data to a variable 18 $ p = new Person; 19 // modify the attribute value to determine the object-oriented value transfer method 20 $ p-> name = 'jesse '; 21 // if the value is successfully modified, the value is 22 echo $ p-> name; // jesse23?>
Case Explanation:
Here, the variable assignment method is used to compare with the object assignment method. The Assignment Method in line 5th of the code is "Copy assignment", so the source value (the value of $ a) is modified) the value of $ B is not affected. The memory relationship between $ a and $ B is as follows:
In the Code 20 line, the data type is assigned to the $ p variable, and the value inside the object is successfully modified through $ p. Compared with the value passing method of the variable, it is proved that this is a reference transfer value. The memory relationship diagram is as follows:
After understanding these two basic methods, we will deepen the object-oriented value transfer method. Please take a look at the Code:
1 <? Php 2 class Person 3 {4 public $ name; 5 public $ age; 6} 7 // assign an object type data value to a variable 8 $ p = new Person; 9 // you can modify the attribute value to determine the object-oriented value transfer method 10 $ p-> name = 'jesse '; 11 // assign the object to another variable 12 $ m = $ p; 13 // modify the attribute value of another variable 14 $ m-> name = 'marry '; 15 // result 16 echo $ p-> name, $ m-> name; 17?>
The first line of code is the most "eye-catching" code in this article. The right side of the equal sign is an object and the left side is a variable. This is a sharp question, $ m is to copy an object? Or by reference? The memory relationship of the Code is as follows:
Therefore, the attribute values of the last two objects are modified to Marry !!!
So what will happen when passing values by reference?
1 <? Php 2 class Person 3 {4 public $ name; 5 public $ age; 6} 7 // assign an object type data value to a variable 8 $ p = new Person; 9 // you can modify the attribute value to determine the object-oriented value transfer method 10 $ p-> name = 'jesse '; 11 // assign the object to another variable 12 $ m = & $ p; 13 // modify the attribute value of another variable 14 $ m-> name = 'marry '; 15 // result 16 echo $ p-> name, $ m-> name; 17?>
------ Create By Jesse 2018.01.22