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.
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 past, I have been guilty of errors in code when reusing local loop variables like i
and j
...]
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:
$foo = $_GET['input'];
# use $foo
if ($a == $b) {
$foo = 1;
} else {
# $foo = 2; # Commented out for some reason
}
# Value $foo supplied in URL leaks through to here
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.
What about when you need call another method of the DbObject
?
I prefer give the variable name what it is:
$dbo = new DbObject(new Database(), 'items');
$total_count = $dbo->count_all();
//so you call still do things next
$result = $dbo->get_all();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With