回收或重用变量可以接受吗? [英] is it acceptable to recycle or reuse variables?

查看:264
本文介绍了回收或重用变量可以接受吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到无处不在,我似乎无法以某种方式找到答案。是否可以(好或坏的做法)重用或回收变量?它工作,我已经使用这种方法几次,但我不知道我应该做这个不是。我试图摆脱使用静态方法,并进入依赖注入。



在这个例子中,$ table_name设置在其他地方。

  class DbObject {
private $ db = NULL;
protected $ table_name;

public function __construct($ dbh,$ item){
$ this-> db = $ dbh;
$ this-> $ table_name = $ item;
}

//计算数据库中的项目//
public function count_all(){
try {
$ sql ='SELECT COUNT(*) FROM'。 $这 - >表名;

$ stmt = $ this-> db-> query($ sql);
$ stmt-> setFetchMode(pdo :: FETCH_COLUMN,0);
$ result = $ stmt-> fetchColumn();
return $ result;
} catch(PDOException $ e){
echo $ e-> getMessage());
}
}

要使用这个,我会使用它: / p>

  $ total_count = new DbObject(new Database(),'items'); 
$ total_count = $ total_count-> count_all();

这是一个可以接受的代码方式吗?
感谢您的帮助。

解决方案

为了不同的目的重用变量是等待发生的维护错误。



这是不好的做法。一个很好的命名变量可以帮助代码理解。



在弱类型的动态语言(如PHP)中,重用变量非常脆弱。



遇到生产代码中的错误(等等,我认为是我的!),其中重用本地循环变量,如i和j导致错误...]


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

这篇关于回收或重用变量可以接受吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆