Magic Methods in PHP ( __sleep() ) OOP Concept in PHP In Hindi/Urdu

Опубликовано: 24 Март 2026
на канале: Thakur Pavinder
926
20

__sleep() is called when you serialize() an object.

serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.

Serializing an object means converting it to a bytestream representation that can be stored in a file. This is useful for persistent data; for example, PHP sessions automatically save and restore objects.

The __sleep( ) method is called on an object just before serialization; it can perform any cleanup necessary to preserve the object's state, such as closing database connections, writing out unsaved persistent data, and so on. It should return an array containing the names of the data members that need be written into the bytestream. If you return an empty array, no data is written.
==================FOLLOW ME ==================

Subscribe My Channel for New Releases!

------------------- QUESTIONS? ------------------------------

Leave a comment below and I or someone else can help you.

For quick questions
Email me [email protected]

Thanks for all your support!