Home  >  Article  >  Backend Development  >  The use and precautions of PHP's reference operator &

The use and precautions of PHP's reference operator &

高洛峰
高洛峰Original
2016-10-17 11:15:403142browse

PHP’s reference operator &, anyone familiar with C knows that there is something called a pointer in C, and a pointer points to a memory address. This & also has the same function.

Look at the following code:

$source="110";
$a=$source;
$b=&$source;
$source="120";
echo $a."\r\n",$b;

After running this code, you will find a problem. The value of $a does not change according to the value of $source in the fourth line of code. It is still the original assignment "110". This is good. Understand, when $a is assigned, the value of $source is 110. She just copied the value of $source to herself.

Obviously you will also notice that the value of variable $b has changed. $a and variable $b are assigned almost at the same time. Why is there such a huge difference? One is responsible for beating people and the other is responsible for saving people. The difference is big enough!

This is a problem with PHP’s reference operator &. Because variable $b is applied to & when assigning value, $b does not copy “110” to itself but directly points to the home of $source. In the future, $source It’s him $b. No matter how $source changes, it will lead to changes in $b - much like the relationship between a host and two monitors. Since this is the relationship, changes in $b will of course lead to changes in $source

See:

$b=122;
echo $source;

The output result is: 122. You see, these two variables are one "person" from now on. Don't bully them!

In fact, for the sake of program readability and subsequent programming misoperations, I do not recommend using the & reference operator, think about it. Before row 10,000, you used $b=&$source; and you may not remember it after row 10,000. If you accidentally assign the wrong value, it will be enough for you to drink when debugging! Haha...

In fact, this operator is more used in database connections, because when we create database connection objects, we often only need one, and too many are useless.

Suppose we have a class:

class MysqlConnect{} //用来创建数据库连接,那么我们每次调用的时候可以这样写
  
$conn=& new MysqlConnect();

This way of writing can ensure that the database connection will not be repeatedly created, consuming system resources. But if you really need multiple different connections, you must not write it like this.

Of course, the PHP reference operator is indeed useful when creating objects. If you create thousands of objects in a PHP script, the system overhead is indeed very high. If there is no need to create multiple ones, try to use &!


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