The __sleep() magic method is mainly responsible of customizing the data collection while serialization of a class.

Let’s first look at a simple example on how to serialize & unserialize a class in PHP

Serialize a class

class DevPeel
	public $name = 'devpeel';

$class = new DevPeel();


Now let’s take the serialized string and try to unserialize it.

Unserialize a class

$serialized = 'O:7:"DevPeel":1:{s:4:"name";s:7:"devpeel";}';
$class = unserialize($serialized);


and the output:

object(__PHP_Incomplete_Class)#1 (2) {
  string(7) "DevPeel"
  string(7) "devpeel"

Another Example (Job Dispatch)

Let’s see a simple example of serializing data of a job assigned to email user something. We’ll first serialize the data and later try to unserialize it.

class SendUserEmail
	protected $user;

	public function __construct(User $user){
		$this->user = $user;

	public function handle(){
		var_dump('send email');

class User
	protected $data =[

	public function __sleep(){
		return ['data'];

$user = new User();
$job = new SendUserEmail($user);

$string = serialize($job);

& the output:

string(111) "O:13:"SendUserEmail":1:{s:7:"*user";O:4:"User":1:{s:7:"*data";a:1:{s:5:"email";s:17:"";}}}"

If required to put this into our database, we probably need to base64_encode this string.
Now let’s convert it back using unserialize helper function, likeso

$unserialized = unserialize(base64_decode($string));

& the unserialized output:

object(SendUserEmail)#3 (1) {
  object(User)#4 (1) {
    array(1) {
      string(17) ""

Now after unserialzing, we can still access to methods of the class likeso,


It will run the handle() method inside of SendUserEmail class & we can carry out further processes.

You may also Like