serialize() turns a value into a string that unserialize() restores; sessions use it. __serialize() (PHP 7.4) returns the array to store, and __unserialize() rebuilds the object without its constructor. PHP 8.5 soft-deprecates __sleep()/__wakeup(); bare Serializable is deprecated since 8.1.
<?php
final class Cart {
public function __construct(public string $customer, private array $items = []) {}
public function count(): int { return array_sum($this->items); }
public function __serialize(): array {
return ['v' => 2, 'customer' => $this->customer, 'items' => $this->items];
}
public function __unserialize(array $d): void { // no constructor runs
[$this->customer, $this->items] = [$d['customer'], $d['v'] >= 2 ? $d['items'] : []];
}
}
echo $s = serialize(new Cart('Ann Lee', ['BK-101' => 2])), "\n";
echo unserialize($s, ['allowed_classes' => [Cart::class]])->count(), "\n";
echo get_class(unserialize(str_replace('Cart', 'Oops', $s), ['allowed_classes' => false]));Output
O:4:"Cart":3:{s:1:"v";i:2;s:8:"customer";s:7:"Ann Lee";s:5:"items";a:1:{s:6:"BK-101";i:2;}}
2
__PHP_Incomplete_Class