This article mainly introduces that PHP should avoid using variables of the same name (splitting temporary variables). When a temporary variable is assigned multiple times, it will be split into multiple variables, unless it is a loop counter, you can refer
This article mainly introduces that PHP should avoid using variables of the same name (splitting temporary variables). When a temporary variable is assigned multiple times, it will be split into multiple variables, unless it is a loop counter, you can refer
When a temporary variable is assigned multiple times, it is split into multiple values unless it is a cyclic counter.
Motivation
Temporary variables have different purposes. For example, they can be used as counters in a loop, to save the result set in a loop, or to save the computation results of a lengthy expression.
These types of variables (containers) should be assigned only once. If a temporary variable with the same name is assigned multiple responsibilities, the code readability will be affected. At this time, we should introduce a new temporary variable to make the code clearer and easier to understand.
Some performance-oriented people may say that introducing a new variable will occupy more memory. This is true, but registering a new variable won't suck up the server memory. We are not living in the 386 era, rather than making the so-called Optimization in these boring details, it is better to optimize the real system performance bottlenecks, such as databases and network connections. Moreover, clear and easy-to-understand code is easier to refactor, discover bugs, or solve performance problems.
Example Code
Most of the time, we use the same $ temp variable to calculate different attributes of an object. This is common. For example, the following example:
The Code is as follows:
Function rectangle ($ width = 1, $ height = 1 ){
$ Temp = 2 * ($ width + $ height );
Echo "Perimter: $ temp
";
$ Temp = $ width * $ height;
Echo "Area: $ temp ";
}
As you can see, $ temp is used twice to calculate the perimeter and area of the rectangle. This example looks very intuitive and clear, but the actual project code may be far more complex than this example. If we change the code to the following, no matter how complicated the code is, there will be no confusion.
The Code is as follows:
Function rectangle ($ width = 1, $ height = 1 ){
$ Perimeter = 2 * ($ width + $ height );
Echo "Perimter: $ perimeter
";
$ Area = $ width * $ height;
Echo "Area: $ area ";
}
Declare a new temporary variable for different things (such as expressions). In most cases, performance is not a problem, and readability is very important.