Tag Archives: PHP __wakeup()

PHP use __Sleep() and __wakeup() method serializes the object

If: Notice: serialize(): “DIY” returned as member variable from__ The solution of sleep() but do error

<?php
header('content-type:text/html;charset=utf-8');
class SportObject{
	protected $type="DIY";
	public function getType(){
		return $this->type;
	}
	public function __sleep(){
		echo 'Use the serialize() function to save the object to a text file, database, etc. <br>';
		return array('type'); //Note here, this should return an array, not return $this on the ebook Of course the paper book is the correct way to write it.
	}
	public function __wakeup(){
		echo 'When this data is needed, use the unserialize() function on the serialized string to convert it back to an object<br>';
	}
}
$mybook=new SportObject();
$a=serialize($mybook);
echo 'Serialized string: '. $a."<br>";
$b=unserialize($a);
echo 'Restored member variable.'.$b->getType();
?>

Output results:

Use the serialize() function to save the object, which can be stored in text files, databases, etc.
the serialized string: O: 11: “sportobject”: 1: {s: 7: “* type”; s: 3: “DIY”;}
when the data is needed, use the unserialize() function to operate the serialized string and convert it back to the object
restored member variable: DIY