Home  >  Article  >  Backend Development  >  The difference between php reference and copy

The difference between php reference and copy

王林
王林Original
2019-09-23 13:14:303260browse

The difference between php reference and copy

Regarding value passing and reference passing, the explanations in books are relatively cumbersome, but they always appear in PHP interviews. Below, I will use a life example to help you understand the difference between them.

Step 1

Suppose we go to a hotel to book a room. We compare the hotel's house number to a variable name, and we use the number of people in the room as the variable name. The process of assignment

<?php
$k1=2;//$k1号房间住了2个人
$k2=$k1;//恰巧今天$k1号房间维修,把$k1号房间的人放到$k2房间里面
$k1=10;//假设$k1维修好了,又住进10个人,那么这就是值传递。
echo  "$k1号房间:".$k1."个人";//10
echo  "$k2号房间:".$k2."个人";//1
?>

Characteristics of value transfer:

1. Value equality

That is, $k1 to $k2 The people in the room are equal.

2. Mutual independence and no influence on each other

That is to say, the number of guests in my $k1 room and the number of guests in my $k2 room do not affect each other. . This is called: "Different ways do not work together."

Second step

Take the above example and assume that our room $k1 is hung up by the maintenance worker with two house numbers $k1 and $k2 to understand

<?php
$k1=2;//$k1号房间住了2个人
$k2=&$k1;//恰巧今天$k1号房间挂上"$k1"和“$k2”两个门牌号
$k1=10;//假设$k1又住进10个人,那么这就是引用传递。
echo  "$k1号房间:".$k1."个人";//10
echo  "$k2号房间:".$k2."个人";//10因为门牌$k1房间的客人就是门牌$k2里面的客人
?>

Characteristics of reference passing:

mutual influence, that is to say, how many guests come in $k1, and how many guests are displayed in $k2, which is called "tied on a rope" The grasshopper".

Difference

1. Difference in usage

The symbol passed by the value is =

quote The transfer symbol is &

2. The difference in meaning

Value transfer means that variables are transferred without affecting each other, while reference transfer means that two variables point to the same space. influencing each other.

Recommended tutorial: PHP video tutorial

The above is the detailed content of The difference between php reference and copy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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