PHP should avoid using the same name variable (split temporary variable), PHP variable
When a temporary variable is assigned multiple times, it is split into multiple, unless it is a loop counter.
Motivation
There are many different uses for temporary variables. For example, they can be used as counters in a loop, save a result set in a loop, or save the results of a lengthy expression, and so on.
These types of variables (containers) should be assigned only one time. If a temporary variable with the same name is assigned multiple responsibilities, it will affect the readability of the code. At this point we should introduce a new temporary variable to make the code clearer and easier to understand.
Some performance-conscious people may say that introducing a new variable will take up more memory. That's true, but registering a new variable doesn't suck up the server's memory, so be assured that we're not living in 386 times, rather than doing so-called optimizations on these silly minutiae, to optimize real system performance bottlenecks, such as databases, network connections, and so on, and clearly understandable code is easier to refactor, Find bugs, or troubleshoot performance issues, and more.
Example Code
Many times, we use the same $temp variable to calculate the different properties of an object, which is more common, such as the following example:
Copy the Code code 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, the $temp was used two times to calculate the circumference and area of the rectangle respectively. This example looks very straightforward, but the actual project code may be much more complicated than this one, and if we change the code to look like this, it won't be confusing no matter how complex the code is.
Copy the Code code as follows:
function Rectangle ($width =1, $height =1) {
$perimeter = 2 * ($width + $height);
echo "Perimter: $perimeter
";
$area = $width * $height;
echo "area: $area";
}
Declaring a new temporary variable for something different (such as an expression) is not a problem for most of the time, and readability is very important.
http://www.bkjia.com/PHPjc/978726.html www.bkjia.com true http://www.bkjia.com/PHPjc/978726.html techarticle PHP should avoid using the same name variable (split temporary variable), PHP variable when a temporary variable is assigned multiple times, then split it into multiple, unless it is a loop counter. ...