2009-08-24, 08:26 PM
Resuing a variable is bad because novice programmers forget to release the memory which causes leaks etc. You can reuse a variable as long as it makes sense, and it isnt being used/have already been released.
There's one rule I always followed, especially when it comes to parsing/fetching database data. That is after you finished processing it, free it right after. An example of that is:
$res = mysql_query('SELECT blah from some_db.some_table');
while($row = mysql_fetch_object($res))
{
// do something
}
mysql_free_result($res);
As you can see, $row get reused multiple times. Its fine, because it holds instances of the same entity.
As for the comment about pointers in linked list and tree, that's another dimension reusing variables. While, technically, you only remapping head/tail rather than freeing > assigning values to it (as per your example), it shows that it is a sensible situation to resuse those variables.
When in doubt, create a new variable.
There's one rule I always followed, especially when it comes to parsing/fetching database data. That is after you finished processing it, free it right after. An example of that is:
$res = mysql_query('SELECT blah from some_db.some_table');
while($row = mysql_fetch_object($res))
{
// do something
}
mysql_free_result($res);
As you can see, $row get reused multiple times. Its fine, because it holds instances of the same entity.
As for the comment about pointers in linked list and tree, that's another dimension reusing variables. While, technically, you only remapping head/tail rather than freeing > assigning values to it (as per your example), it shows that it is a sensible situation to resuse those variables.
When in doubt, create a new variable.

