Home > Article > Backend Development > You should avoid using variables with the same name (split temporary variables) in PHP, php variables_PHP tutorial
When a temporary variable is assigned multiple times, split it into multiple ones. Unless it's a loop counter.
Motivation
Temporary variables have many different uses. For example, they can be used as counters in loops, to save result sets in loops, or to save the calculation results of a lengthy expression, etc.
These types of variables (containers) should only be assigned once. If a temporary variable with the same name is assigned multiple responsibilities, it will affect the readability of the code. At this time we should introduce a new temporary variable to make the code clearer and easier to understand.
Some people who focus on performance may say that introducing a new variable will take up more memory. This is true, but registering a new variable will not drain the server memory. Please rest assured that we are not living in the 386 era. Rather than engaging in so-called optimizations on these boring details, it is better to optimize the real system performance bottlenecks. For example, databases, network connections, etc., and clear and easy-to-understand code is easier to refactor, find bugs, or solve performance problems, etc.
Example Code
Many times, we use the same $temp variable to calculate different attributes of an object. This situation is relatively common, such as the following example:
Copy code 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 complicated than this example. If we change the code to the following, there will be no confusion no matter how complicated the code is.
Copy code 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 something different (like an expression). Most of the time performance is not an issue, but readability is.