Variable references for PHP constants and variables
Variable Reference
Variable Reference Many teachers like to use C language pointers to explain. As people with so many years of development and teaching experience - most people who learn PHP don't understand C language at all.
Using a pointer in C language to explain variable reference, we feel that it is enough. Moreover, it is not conducive to learning by friends who do not have a foundation in C language.
Regarding the knowledge points of variable reference, please use our explanation as the basis for understanding!
Let’s compare the execution results of the two pieces of code:
There is no difference in the first piece of code. It is exactly the same as our original PHP code:
<?php $fo = 5; //$fo的值为5,将5赋值 $bar = $fo; //$bar的值原来为5,现在将值改为6 $bar = 6; //$bar的结果为6 echo $bar.'<br />'; //$fo的结果为5 echo $fo.'<br />'; ?>
The second code:
<?php $fo = 5; //注意,加上了一个&符哟 $bar = &$fo; $bar = 6; //$bar的结果为6 echo $bar.'<br />'; //$fo的结果为6 echo $fo.'<br />'; ?>
Why do both results become 6?
I often give you this example. We can imagine it this way: a variable name corresponds to a data value. As shown below:
And adding & (after the and character) points the variables to the same storage space, as shown below:
That is, no matter how the value of $fo or $bar changes, $fo changes to $bar, and $bar changes, $fo will also change.
Let me give you an unreliable example to help you understand:
You have a puppy at home called Wangcai. There is another puppy named Goudan. One day, you ate the dog’s eggs. If you give the name Goudan to Wangcai
, then whether you hit Goudan or Wangcai, you will hit the same dog.
Note: If you understand, know, and are familiar with C language pointers. You can use pointers to understand it yourself, which is beyond the scope of this article.