問題描述
我嘗試使用 memcache 在 PHP 中緩存我的 User 對象,但是在使用 PDO 時出現(xiàn)錯誤.我添加了一個 __sleep 和一個 __wakeup 函數(shù).
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()
(這是您在后一種情況下已經(jīng)執(zhí)行的操作):
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.
這篇關(guān)于PDOException: 您不能序列化或反序列化 PDO 實例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!