PHP PDO – 无法序列化或反序列化PDO实例

我需要将PDO连接从控制器传递到购物车类,

function __construct($connection) 
{
    $this->cart = new cart($connection);
}

但我认为问题出在serialize()

public function render_page() 
{

    if (!isset($_SESSION[SESSION_CART]))
    {
       $cart =  $this->cart;
    }
    else 
    {
       $cart = unserialize($_SESSION[SESSION_CART]);
    }

    $_SESSION[SESSION_CART] = serialize($cart); 

 }

我收到这个错误,

Fatal error: Uncaught exception ‘PDOException’ with message ‘You
cannot serialize or unserialize PDO instances’ in
C:\wamp\www\store_2012_MVC\local\controllers\class_base_extended_cart.php:89
Stack trace: #0 [internal function]: PDO->__sleep() #1
C:\wamp\www\store_2012_MVC\local\controllers\class_base_extended_cart.php(89):
serialize(Object(cart)) #2
C:\wamp\www\store_2012_MVC\local\controllers\class_factory.php(75):
base_extended_cart->render_page() #3
C:\wamp\www\store_2012_MVC\index.php(69): factory->render() #4 {main}
thrown in
C:\wamp\www\store_2012_MVC\local\controllers\class_base_extended_cart.php
on line 89

我怎样才能解决这个问题?

或者我可以使用其他东西而不是serialize()?

编辑:

我用__sleep和__wakeup魔术方法尝试过但仍然得到同样的错误,

class database_pdo
{
    # database handler
    protected $connection = null;

    # make a connection
    public function __construct($dsn,$username,$password)
    {
        try 
        {

            $this->connection = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

        }
        catch (PDOException $e) 
        {
            # call the get_error function
            $this->get_error($e);
        }
    }

    # don't forget to add getter method to get $this->connection, it's just a good practice.
    public function get_connection()
    {
        return $this->connection;
    }

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

    public function __wakeup()
    {
        $this->connection;
    }

}
最佳答案
看看__sleep和__wakeup魔术方法.
http://us.php.net/manual/en/language.oop5.magic.php#object.sleep

它们允许您指定哪些属性被序列化以及哪些属性被忽略.问题在于您需要定期传递PDO对象的实例.

转载注明原文:PHP PDO – 无法序列化或反序列化PDO实例 - 代码日志