Why can't a PDO object be serialized?

前端 未结 2 1374
-上瘾入骨i
-上瘾入骨i 2021-01-14 02:17

I am making a multi-threaded CLI-PHP application and need to serialize PDO object to pass it between work inside the thread, and wake it up from a sleeping thre

2条回答
  •  春和景丽
    2021-01-14 02:49

    What's being done at http://php.net/manual/en/language.oop5.magic.php is creating a wrapper that can be serialized since the PDO link itself cannot be.

    dsn = $dsn;
            $this->username = $username;
            $this->password = $password;
            $this->connect();
        }
    
        private function connect()
        {
            $this->link = new PDO($this->dsn, $this->username, $this->password);
        }
    
        public function __sleep()
        {
            return array('dsn', 'username', 'password');
        }
    
        public function __wakeup()
        {
            $this->connect();
        }
    }?>
    

    The PDO object apparently does not keep the dsn, user, pwd after connecting, and so cannot be directly serialized. But if you created a wrapper like in the example above, where you stored this information, you could serialize the wrapper. Then when you unserialize, it will create a new PDO object and reconnect by passing the credentials in from the wrapper to PDO.

提交回复
热议问题