<?php
namespace app\shop\drive;
class Redis {
public $handler;
public function __construct(){
$redis = new \Redis();
$redisConf = config('cache.redis');
$redis->connect($redisConf['host'], $redisConf['port']);
$redis->auth($redisConf['password']);
$this->handler = $redis;
}
public function __destruct(){
$this->handler->close();
}
}
In controller
...
public $redis, $prefix;
protected function _initialize(){
$this->initRedis();
var_dump($this->redis->info()); //Error, redis connection has been closed
}
private function initRedis()
{
$redis = new Redis;
$this->redis = $redis->handler;
var_dump($this->redis->info()); //Normal
$this->prefix = config('cache.redis')['prefix'];
}
1. What is the reason?
2. Is it necessary to manually close the redis connection?
The
__destruct() method is executed when the object is destroyed
In PHP, after a function or method is executed, its internal variables will be destroyed (except static variables). Therefore, the $redis variable will be destroyed after initRedis is executed, and _ in the Redis class will be executed. _destruct() method, even if you assign the handle to the redis attribute, the redis connection has been closed in __destruct()