I've looked everywhere, and I can't seem to find an answer one way or another. Is it acceptable (good or bad practice) to reuse or recycle a variable? It works, and I've used this method a few times, but I don't know if I should be doing this or not. I'm trying to get away from using static methods, and moving into dependency injection.
in this example, the $table_name is set elsewhere.
class DbObject {
private $db = NULL;
protected $table_name;
public function __construct($dbh, $item) {
$this->db = $dbh;
$this->$table_name = $item;
}
// counts items in database //
public function count_all() {
try {
$sql = 'SELECT COUNT(*) FROM ' . $this->table_name;
$stmt = $this->db->query($sql);
$stmt->setFetchMode(pdo::FETCH_COLUMN, 0);
$result = $stmt->fetchColumn();
return $result;
} catch (PDOException $e) {
echo $e->getMessage());
}
}
To use this I would use it like this:
$total_count = new DbObject(new Database(), 'items');
$total_count = $total_count->count_all();
Is this an acceptable way to code? Thanks for your help.
If you like using common names often through out a script (e.g.
$i
for counting iterations in a loop) you should have no problems if you make it a habit to callunset()
whenever you're done with using a variable in a particular case.People tend to re-use "throw-away" variables like i and j, but it is usually bad form to reuse other local variables for a different purpose. That leads to reader confusion about where a variable is initialized and whether updates in one part of the code will affect another part of the code. There may also be ill-effects on a compiler's optimization suite (perhaps suggesting a variable should be saved when it isn't necessary).
Sometimes the variables could conflict or you could get them mixed out. So I would only reuse
$i
and$row
unless youunset()
the variable when you are done.What about when you need call another method of the
DbObject
?I prefer give the variable name what it is:
Reusing variables for different purposes is a maintenance error waiting to happen.
It's bad practice. A well named variable can do wonders for aiding code comprehension.
Reusing variables is especially fragile in weakly typed dynamic languages such as PHP.
[In the dim past I have come across errors in production code (wait, I think it was mine!) where reuse of local loop vars like i and j lead to errors...]
The main reason to avoid reusing variables is that if you reuse a variable without properly re-initializing it, the old value will "leak" through, causing unpredictable effects and even security vulnerabilities. For example:
Generally, reuse of variables will not damage performance if the compiler uses single-static assignment form (SSA) as an intermediate form during optimization (part of what SSA does is giving separate names to such reused variables). So don't worry about performance - worry about maintainability.