我需要将PDO连接从controller
传递到cart
类中,
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);
}
我收到此错误,
致命错误:未捕获的异常"PDOException",消息为"您" 无法序列化或反序列化 PDO 实例 C:\wamp\www\store_2012_MVC\local\controllers\class_base_extended_cart.php:89 堆栈跟踪:#0 [内部函数]:PDO->__sleep() #1 C:\wamp\www\store_2012_MVC\local\controllers\class_base_extended_cart.php(89): 序列化(对象(购物车)) #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} 扔进去 C:\wamp\www\store_2012_MVC\local\controllers\class_base_extended_cart.php 在第 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;
}
}
PDO对象包含指向数据库的活动链接(数据库可能具有事务启动或数据库会话设置和变量)。
您无法序列化 PDO 对象,因为上述内容会丢失并且无法自动重新建立。
您应该重新设计您的类以使用单独的类(专用于保存数据库连接)静态访问当前数据库链接,而不是将引用保存在成员变量中(我假设当您执行 new cart($connection))时会发生这种情况)。
看看__sleep和__wakeup魔法方法。http://us.php.net/manual/en/language.oop5.magic.php#object.sleep
它们允许您指定序列化哪些属性以及忽略哪些属性。问题是您需要定期传入 PDO 对象的实例。