2012-06-07 78 views
4

我需要通过从controller一个PDO连接到cart类,PHP 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; 
    } 

} 
+1

注意 - 如果你的类继承自PDO并且你克隆了这个对象,你也会得到这个错误。在我的情况下,我设置$ obj-> pdo在克隆之前为空。 – jerrygarciuh

回答

1

看看的__sleep和__wakeup魔术方法。 http://us.php.net/manual/en/language.oop5.magic.php#object.sleep

它们允许您指定哪些属性被序列化,哪些被忽略。存在的问题是,您需要定期传入PDO对象的实例。

+0

感谢您的回答。我刚刚尝试过它们,但仍然遇到同样的错误,请你看看我上面的编辑。谢谢。 – laukok

+1

你必须扭转它。通过__sleep,你可以返回一系列想要序列化的属性。重点是能够排除不可序列化的属性。例如:你的连接属性。我之所以说这可能不是最好的解决方案,是因为任何时候您从$ _SESSION全局访问购物车时,都必须重置连接属性。像... $ cart = $ _SESSION ['cart']; $ cart-> set_connection($ db) –

+0

感谢您的回复。我认为我已经对我的班级进行了返工... – laukok

3

PDO对象包含到数据库(可能有事务启动或数据库会话设置和变量)的活动链接。

您无法序列化一个PDO对象,因为上述内容会丢失并且无法自动重新建立。

你应该重新设计你的类,使用一个单独的类(专用于保存数据库连接)来静态访问当前数据库链接,而不是在成员变量中保存一个引用(当你做新购物车时,连接)))。

+1

由于〜PHP 5.3.0它似乎__sleep和__wakeup已被标记为PDOStatement和PDO的最终版,所以没有更多的技巧可能:) –

相关问题