回收或重用变量可以接受吗? [英] is it acceptable to recycle or reuse variables?
问题描述
在这个例子中,$ 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屋!