Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP Object Serialization
Object serialization in PHP converts an object into a string representation (byte-stream) that can be stored or transmitted. The serialize() function creates this string containing all object properties, while unserialize() reconstructs the object from the string.
Syntax
// Serialize an object $serialized_string = serialize($object); // Unserialize back to object $object = unserialize($serialized_string);
Basic Example
Let's create a simple class and demonstrate serialization −
<?php
class Person {
private $name;
private $age;
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
function getName() {
return $this->name;
}
function getAge() {
return $this->age;
}
}
// Create object
$person = new Person("Alice", 25);
// Serialize the object
$serialized = serialize($person);
echo "Serialized: " . $serialized . "
";
// Unserialize back to object
$unserialized_person = unserialize($serialized);
echo "Name: " . $unserialized_person->getName() . "
";
echo "Age: " . $unserialized_person->getAge();
?>
Serialized: O:6:"Person":2:{s:11:"Personname";s:5:"Alice";s:10:"Personage";i:25;}
Name: Alice
Age: 25
Storing Serialized Objects in Files
You can save serialized objects to files for persistent storage −
<?php
class Product {
public $name;
public $price;
function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
}
// Create and serialize object
$product = new Product("Laptop", 999.99);
$serialized = serialize($product);
// Save to file
file_put_contents("product.txt", $serialized);
// Read from file and unserialize
$data = file_get_contents("product.txt");
$restored_product = unserialize($data);
echo "Product: " . $restored_product->name;
echo "Price: $" . $restored_product->price;
?>
Key Points
- Properties preserved: All object properties are stored in the serialized string
- Methods not stored: Only data is serialized, not the methods
- Class definition required: The class must be defined before unserializing
- Private/protected access: Property visibility is maintained after unserialization
Conclusion
PHP object serialization provides an easy way to convert objects to strings for storage or transmission. Use serialize() to convert objects and unserialize() to restore them, ensuring the class definition is available during unserialization.
Advertisements
