PHP 5 Tutorial - __sleep() Magic Method
This tutorial will guide you through the __sleep() Magic Method. The __sleep() magic method in PHP5 gets called while serializing an object in PHP5. Serializing is required to pass complex data across the network or PHP pages. It is also used to store data(files, database, cookies etc). With this magic method call we can define the way how the data object will be stored. The __sleep() method should be used along with __wakeup() magic method. The __wakeup() magic method is called while unserializing the data and restores the serialized object to normal form.
Syntax:
< ? function __sleep() { ... return serialised data; } ?>
Example - Basic __sleep() Magic Method Call
< ? class magicmethod { function __sleep() { echo "Performing Clean-Up Operation Before Serializing Data "; return array("Serialized Data","1","2","3"); } } $a = new magicmethod(); $serializedata = serialize($a); echo $serializedata; ?>
Output:
Performing Clean-Up Operation Before Serializing Data
O:11:”magicmethod”:4:{s:15:”Serialized Data”;N;s:1:”1″;N;s:1:”2″;N;s:1:”3″;N;}
Explanation for the Example:
Here i am trying to serialize the object of magicmethod class.
Now the PHP Compiler calls the __sleep() Magic method which return an array having the serialized values
Similar Posts
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.


Comments
No comments yet.
Leave a comment