PHP PDO - cannot serialize or unserialize PDO instances

I need to pass the PDO connection to the cart class from controller ,

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

but I think the problem is serialize()

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

I get this error

Fatal error: throw a "PDOException" exception with the message "You cannot serialize or unesterialize 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 C: \ WAMP \ WWW \ store_2012_MVC \ Local \ controllers \ class_base_extended_cart.php on line 89

How can i fix this?

Or can I use something else instead of serialize() ?

EDIT:

I tried it with the magic methods __sleep and __wakeup , but still getting the same error,

 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 just a good practice. public function get_connection() { return $this->connection; } public function __sleep() { return array('connection'); } public function __wakeup() { $this->connection; } } 
+4
source share
2 answers

Take a look at the __sleep and __wakeup magic methods. http://us.php.net/manual/en/language.oop5.magic.php#object.sleep

They allow you to specify which properties will be serialized and which are ignored. The problem is that you will need to regularly pass an instance of your PDO object.

+1
source

PDOs contain active database references (which may have initiated transactions or db session settings and variables).

You cannot serialize a PDO object because the above is lost and cannot be automatically restored.

You have to redo your classes in order to access the current database link statically using a separate class (dedicated to storing db links) instead of storing the link in a member variable (I assume this happens when you make a new basket ($ connection) )).

+3
source

Source: https://habr.com/ru/post/1416644/


All Articles