我建议你用这个来修改你的单例逻辑。
class Crud
{
private $pdo = null; # Storing PDO connection
private $table = null; # Storing table name
private static $crud = []; # Static attribute that contains a self instance
# ----------------------------------------
# Class constructor -> PUBLIC method
# ----------------------------------------
public function __construct($connection, $table = 'default')
{
if (!empty($connection)) {
$this->pdo = $connection;
} else {
echo 'Conexão inexistente!';
exit();
}
if (!empty($table) && $table !== 'default') {
$this->table =$table;
}
}
# ----------------------------------------
# Static public method that returns a Crud class instance
# ----------------------------------------
public static function getInstance($connection, $table = 'default')
{
# Verifying if there's a class instance
if (!isset(self::$crud[$table])) {
try {
self::$crud[$table] = new Crud($connection, $table);
} catch (Exception $e) {
echo 'Error '.$e->getMessage();
}
}
return self::$crud[$table];
}
}
$crud
作为数组,并按表名隔离存储每个实例。
if (!isset(self::$crud[$table])) {
try {
self::$crud[$table] = new Crud($connection, $table);
} catch (Exception $e) {
echo 'Error '.$e->getMessage();
}
}
因此,以下代码的工作方式如下:
Crud::getInstance($pdo); // Create new instance and store it on key 'default'
Crud::getInstance($pdo); // Just return 'default' instance
Crud::getInstance($pdo,'foo'); // Create new instance and store it on key 'foo'
Crud::getInstance($pdo,'foo'); // Just return 'foo' instance