我需要通過從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;
}
}
注意 - 如果你的類繼承自PDO並且你克隆了這個對象,你也會得到這個錯誤。在我的情況下,我設置$ obj-> pdo在克隆之前爲空。 – jerrygarciuh