的config.php
define('DB_TYPE', 'MYSQL');
dbManager.php
incude_once('config.php');
switch ( DB_TYPE ) {
case 'MYSQL': $this->_dataObject = MySqlDB::_getInstance(); break;
case 'PGSQL': $this->_dataObject = PostgreDB::_getInstance(); break;
case 'SQLITE': $this->_dataObject = SqliteDB::_getInstance(); break;
}
这段代码可以在没有案例的情况下重写吗?类似的东西:
$this->_dataObject = DB_TYPE::_getInstance();
这给了我一个错误Fatal error: Class 'DB_TYPE' not found .... in line ...
答案 0 :(得分:2)
也许
$DBClassName = 'MySqlDB';
$this->_dataObject = $DBClassName::_getInstance();
答案 1 :(得分:0)
尝试:
$c = TYPE;
$this->_dataObject = $c::_getInstance();
然而,这段代码看起来可能会受益于依赖注入
class YourClass {
public function __construct(DataObject $dataObject) {
$this->_dataObject = $dataObject;
}
}
然后将数据对象传递给您的类,同时实例化它
答案 2 :(得分:0)
$dbClasses = array(
'MYSQL' => 'MySqlDB',
'PGSQL' => 'PostgreDB',
'SQLITE'=> 'SqliteDB',
};
$dbClass = $dbClasses[DB_TYPE];
$this->_dataObject = $dbClass::_getInstance();