When is __destruct executed in thinkphp5?
世界只因有你
世界只因有你 2017-05-16 13:11:43
0
1
441
<?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?

世界只因有你
世界只因有你

reply all(1)
巴扎黑

The

__destruct() method is executed when the object is destroyed

public $redis, $prefix;
    protected function _initialize(){
        $this->initRedis();    //在initRedis()方法中实例Redis对象,当此方法执行完毕,实例出来的Redis对象就会被销毁,同时会执行Redis类中的__destruct方法,redis连接被关闭
        var_dump($this->redis->info()); //此时initRedis已经执行完毕,redis连接也已经被关闭
    }
    private function initRedis()
    {
        $redis = new Redis;
        $this->redis = $redis->handler;
        var_dump($this->redis->info()); //正常
        $this->prefix = config('cache.redis')['prefix'];
    }

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()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template