PDOException: 您不能序列化或反序列化 PDO 实例

2021-12-26 00:00:00 serialization memcached php pdo

我尝试使用 memcache 在 PHP 中缓存我的 User 对象,但是在使用 PDO 时出现错误.我添加了一个 __sleep 和一个 __wakeup 函数.

I tried to cache my User object in PHP with memcache, but I get an error while using PDO. I added a __sleep and a __wakeup function.

用户.php

/**
 * @var PDO
 */
protected $db;

public function __construct()
{
    $this->db = getInstanceOf('db');
}

public function __destruct()
{

}

public function __sleep()
{
    return array('db');
}

public function __wakeup()
{
    $this->db = getInstanceOf('db');
}

getInstanceOf('db') 返回一个 pdo 对象...

getInstanceOf('db') returns a pdo object...

返回以下错误:

PDOException:您不能在第 41 行的/var/www/test/User.php 中序列化或反序列化 PDO 实例

PDOException: You cannot serialize or unserialize PDO instances in /var/www/test/User.php on line 41

推荐答案

$this->db 很可能是一个 PDO 对象.PDO 对象无法序列化.

It is likely that $this->db is a PDO object. PDO objects can not be serialized.

__sleep() 上删除该对象并将其添加回 __wakeup()(这是您在后一种情况下已经执行的操作):

Remove that object on __sleep() and add it back at __wakeup() (which is what you already do in the later case):

public function __sleep()
{
    return array();
}

不能序列化的对象不能序列化.但是你试过了,所以你得到了例外.这基本上就是整个问题.只是不要告诉 PHP 序列化无法序列化的对象.

You can not serialize objects that can not be serialized. But you tried, so you got the exception. That's basically the whole issue. Just don't tell PHP to serialize objects that can't be serialized.

相关文章