is it acceptable to recycle or reuse variables?

2019-02-23 03:10发布

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.

6条回答
可以哭但决不认输i
2楼-- · 2019-02-23 03:23

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 call unset() whenever you're done with using a variable in a particular case.

查看更多
戒情不戒烟
3楼-- · 2019-02-23 03:29

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).

查看更多
我命由我不由天
4楼-- · 2019-02-23 03:29

Sometimes the variables could conflict or you could get them mixed out. So I would only reuse $i and $row unless you unset() the variable when you are done.

查看更多
混吃等死
5楼-- · 2019-02-23 03:30

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();
查看更多
迷人小祖宗
6楼-- · 2019-02-23 03:31

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...]

查看更多
爷的心禁止访问
7楼-- · 2019-02-23 03:49

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.

查看更多
登录 后发表回答