__serialize & __unserialize
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 49 of 91.
When you need to convert an object to a string for storage or transmission, PHP uses serialization. The __serialize() and __unserialize() magic methods give you control over exactly what data gets saved and how it's restored.
The __serialize() method returns an array of data to be serialized, while __unserialize() receives that array and rebuilds the object:
<?php
class Session {
public function __construct(
private string $userId,
private array $data,
private int $createdAt
) {}
public function __serialize(): array {
return [
'userId' => $this->userId,
'data' => $this->data
];
}
public function __unserialize(array $data): void {
$this->userId = $data['userId'];
$this->data = $data['data'];
$this->createdAt = time();
}
public function getCreatedAt(): int {
return $this->createdAt;
}
}
$session = new Session("user123", ["theme" => "dark"], time());
$serialized = serialize($session);
$restored = unserialize($serialized);
echo "User: " . $restored->getCreatedAt();
Notice how createdAt is excluded from serialization and gets a fresh timestamp when unserialized. This is useful for excluding sensitive data, temporary values, or resources that can't be serialized like database connections.
These methods replaced the older __sleep() and __wakeup() methods in PHP 7.4, offering a cleaner approach where you work directly with data arrays instead of property names.
Challenge
EasyLet's build a user profile caching system that demonstrates how __serialize() and __unserialize() give you control over what data gets saved and how it's restored.
You'll organize your code across two files:
UserProfile.php— Create aUserProfileclass that represents a user's profile with caching capabilities. Use constructor promotion to define private properties for$userId(string),$username(string),$email(string), and$accessToken(string). Add a private$cachedAtproperty that stores when the profile was cached (set it to"not cached"initially in the constructor). Your class needs:__serialize()— Returns an array containing only theuserId,username, andemail. TheaccessTokenis sensitive and should never be serialized. ThecachedAttimestamp will be regenerated on restore.__unserialize()— Restores theuserId,username, andemailfrom the data array. SetsaccessTokento"expired"(since tokens shouldn't persist).getInfo()— Returns a string in the format:"[username] ([email]) - Token: [accessToken] - Cached: [cachedAt]"
main.php— Include the UserProfile file. You'll receive four inputs: a user ID, a username, an email, and an access token. Create aUserProfileinstance with these values. Print three lines:- The original profile's info (before serialization)
- Serialize the profile using
serialize(), then unserialize it usingunserialize()to create a restored profile. Print the restored profile's info. - Print
"Token preserved: yes"or"Token preserved: no"depending on whether the restored profile's token matches the original (hint: it shouldn't match since tokens expire on restore)
This pattern is essential for caching user data safely — you want to store the profile information but never persist sensitive credentials like access tokens. When the profile is restored from cache, the token is marked as expired, forcing the application to obtain a fresh one.
Cheat sheet
The __serialize() and __unserialize() magic methods control what data gets saved during serialization and how objects are restored.
__serialize() returns an array of data to be serialized:
<?php
public function __serialize(): array {
return [
'userId' => $this->userId,
'data' => $this->data
];
}__unserialize() receives the array and rebuilds the object:
<?php
public function __unserialize(array $data): void {
$this->userId = $data['userId'];
$this->data = $data['data'];
$this->createdAt = time();
}Use serialize() to convert an object to a string and unserialize() to restore it:
<?php
$serialized = serialize($session);
$restored = unserialize($serialized);These methods are useful for excluding sensitive data, temporary values, or resources that can't be serialized (like database connections). Properties can be regenerated with fresh values during unserialization.
Try it yourself
<?php
require_once 'UserProfile.php';
// Read inputs
$userId = trim(fgets(STDIN));
$username = trim(fgets(STDIN));
$email = trim(fgets(STDIN));
$accessToken = trim(fgets(STDIN));
// TODO: Create a UserProfile instance with the input values
// TODO: Print the original profile's info (before serialization)
// TODO: Serialize the profile, then unserialize it to create a restored profile
// TODO: Print the restored profile's info
// TODO: Print "Token preserved: yes" or "Token preserved: no"
// depending on whether the restored profile's token matches the original
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern