次のコードがあり、$ redisdb paramを渡して2つのサーバーに接続したいとします。 不幸にも、2番目のインスタンスが最初に接続します。PHPで同じクラスを2回インスタンス化できません
$redis = new RedisHandler();
$redis2 = new RedisHandler('redis2'); //this one gets first $redis connection
私は間違っていますか?
class RedisHandler
{
static $db = null;
public function __construct($redisdb = 'redis') {
// opening db connection
return self::connect($redisdb);
}
static public function connect($redisdb)
{
global $config;
if (self::$db === null)
{
try {
$redisClient = new Redis();
$redisClient -> connect($config[$redisdb]['host'], $config[$redisdb]['port'], $config[$redisdb]['timeout'], null, $config[$redisdb]['reservedInterval']);
$redisClient->setOption(Redis::OPT_READ_TIMEOUT, 100);
if (!$redisClient) { throw new Exception("Can't connect to Redis"); }
} catch (Exception $e) {
die('Failed to connect to Redis '.$e->getMessage());
}
self::$db = $redisClient;
return self::$db;
//return $m;
}
else
{
// return self::$db;
return self::$db;
}
}
}
まあ、1つの接続だけを静的に格納していて、1つのグローバル変数と大きく異なるわけではありません... – deceze