我需要将 PDO 连接传递到一个cart
类中controller
,
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);
}
我得到这个错误,
致命错误:在 C:\wamp\www\store_2012_MVC\local\controllers\class_base_extended_cart.php:89 中未捕获的异常“PDOException”和消息“您无法序列化或反序列化 PDO 实例”堆栈跟踪:#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;
}
}