Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

php - Why can't a PDO object be serialized?

I am making a multi-threaded CLI-PHP application and need to serialize PDO object to pass it between work inside the thread, and wake it up from a sleeping thread using magic methods __sleep() and __wakeup(). However nor the PDO or mysqli extension supports it. The old mysql_*() api did this but it has been deprecated and removed.

<?php
    // Application
    $link = new PDO('mysql:host=localhost;port=3306;dbname=testdatabase', 'root', '');

    $obj = serialize($link);

well generate error

PHP Fatal error: Uncaught exception 'PDOException' with message 'You cannot ser ialize or unserialize PDO instances' in W:workspaceSandboxapplication.php:5 Stack trace:

#0 [internal function]: PDO->__sleep()

#1 W:workspaceSandboxapplication.php(5): serialize(Object(PDO))

#2 {main} thrown in W:workspaceSandboxapplication.php on line 5

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A PDO object contains state that cannot be represented in the serialization format. For example, the PDO object contains an open connection to a database server.

If you were to try to deserialize a serialized PDO object, the __wakeup() method would have to reconnect to the database server. This would require that authentication credentials be stored in a readable manner in the serialized PDO object, which is a security no-no.

I worked on the Zend Framework's Zend_Db component a long time ago, and I deliberately designed the Zend_Db_Adapter object to not be serializable for this reason. Instances of Zend_Db_Table, Zend_Db_Table_Row, etc. could be serializable, but could not be "live" after deserialization until you assigned it a freshly connected Zend_Db_Adapter instance.

Also, there's no guarantee that the database server would be reachable at the time you deserialize the PDO object. It's unclear whether this means the deserialization would be considered "failed."

The same restrictions on serialization apply to other resources such as sockets or file handles.

See also Why isn't every type of object serializable?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...