PHP5 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
Popular Articles:
- OOPS in PHP 5 – instanceOf Operator
- PHP5 Tutorial – Parsing XML documents in PHP5 using SimpleXML
- Reading Excel Documents from PHP applications
- PHP5 Tutorial – __call() Magic Method
- OOPS in PHP5 – Declaring Class and Initializing Class Object
- Reading Remote URL HTML Source in PHP
- OOPS in PHP 5 Tutorial – Exploring Inheritance
- How to Implement Text to Speech in PHP
- PHP5 Tutorial – __toString() Magic Method
- Exploring Magic Methods in PHP 5


































