我到处寻找,似乎无法以这种或那种方式找到答案.重用或回收变量是否可接受(好的或坏的做法)?它工作,我已经使用过这种方法几次,但我不知道我是否应该这样做.我正试图摆脱使用静态方法,并转向依赖注入.
在此示例中,$ table_name在其他位置设置.
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());
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它,我会像这样使用它:
$total_count = new DbObject(new Database(), 'items');
$total_count = $total_count->count_all();
Run Code Online (Sandbox Code Playgroud)
这是一种可接受的编码方式吗?谢谢你的帮助.