我设置了多个类,他们都需要访问数据库,他们这样做。当我想在另一个类中使用一个函数时,麻烦就来了。
class General
{
private $_db = NULL;
private $_db_one;
private $_db_two;
private $offset;
public function __construct ( PDO $db ) {
$this->_db = $db;
$this->_db_one = 'lightsnh_mage1';
$this->_db_two = 'lightsnh_inventory';
$this->offset = 10800;
}
public function getTableNames() {
$sql = 'SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = "BASE TABLE" AND TABLE_SCHEMA="' . $this->_db_two . '"';
$statement = $this->_db->query($sql);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
这工作正常,然后我的其他班级以相同的方式连接。正如您将在下面的“Distributors”类中看到的那样,我在构造函数中实例化了我的“General”类。在我边写边学习的过程中,我不禁觉得有一种更通用或更有效的连接方式。
class Distributors
{
private $_db = NULL;
private $_db_one;
private $_db_two;
private $_source_tbl;
public $lights;
public function __construct ( PDO $db ) {
$this->_db = $db;
$this->_db_one = 'lightsnh_mage1';
$this->_db_two = 'lightsnh_inventory';
$this->_source_tbl = 'distributors';
// is this the best way to get functions from another class inside of this class? I have 10 classes I will need to repeat this for.
$this->lights = new General($db);
}
public function getInventorySources() {
// calling function from General class inside my distributor class
$tables = $this->lights->getTableNames();
// using result of General function inside of a function from Distributors class
$sql = 'SELECT * FROM `' . $tables . '` WHERE `exclude` = 0';
$statement = $this->_db->query($sql);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}