Home > Article > Backend Development > Detailed explanation of object value transfer method in php
Comparison between variable assignment and object assignment
<?php // 声明一个变量并赋值 $a = 1; // 将数据类型的值 赋值 给一个变量 $b = $a; // 修改$a的值 $a = 2; // $a和$b是两个独立的内存空间修改其中一个另一个不受影响 echo $b; // 1 class Person { public $name; public $age; } // 将对象类型的数据 赋值 给一个变量 $p = new Person; // 通过对属性修改值,来确定面向对象中 对象的传值方式 $p->name = 'jesse'; // 若是成功修改值,则是引用传值 echo $p->name; // jesse ?>
Case explanation:
Here, the variable assignment method and the object assignment method are used In comparison with the assignment method, the assignment method in line 5 of the code is "copy assignment", so when the source value (the value of $a) is modified, the value of $b is not affected. The memory relationship diagram of $a and $b is as follows:
Line 20 of the code assigns the data type to the $p variable, and successfully modifies the value inside the object through $p. Compare the variables The value-passing method proves that this is a reference-passing value. The memory relationship diagram is as follows:
The code line 20 assigns the data type to the $p variable and modifies the interior of the object through $p. The value is successful. Comparing the value transfer method of the variable, it is proved that this is a reference transfer. The memory relationship diagram is as follows:
<?php class Person { public $name; public $age; // 将对象类型的数据 赋值 给一个变量 $p = new Person; // 通过对属性修改值,来确定面向对象中 对象的传值方式 $p->name = 'jesse'; // 将对象赋予另一变量 $m = $p; // 另一变量修改属性值 $m->name = 'Marry'; // 输出源变量 赋值变量访问内部属性的结果 echo $p->name, $m->name; } ?>
The 12th line of code is the most "finishing" code of this article. The right side of the equal sign is is an object, and the left side is a variable, so here comes the sharp question, does $m copy the object? Or pass it by reference? The memory relationship of this code is as follows:
So, the attribute values of the last two objects are modified to Marry!!!
Then passing by reference will What is the situation?
<?php class Person { public $name; public $age; } // 将对象类型的数据 赋值 给一个变量 $p = new Person; // 通过对属性修改值,来确定面向对象中 对象的传值方式 $p->name = 'jesse'; // 将对象赋予另一变量 $m = &$p; // 另一变量修改属性值 $m->name = 'Marry'; // 输出源变量 赋值变量访问内部属性的结果 echo $p->name, $m->name; ?>
For more related content, please visit the PHP Chinese website: PHP Video Tutorial
The above is the detailed content of Detailed explanation of object value transfer method in php. For more information, please follow other related articles on the PHP Chinese website!