-
Notifications
You must be signed in to change notification settings - Fork 4
/
serialization_php74.php
76 lines (58 loc) · 1.61 KB
/
serialization_php74.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
declare(strict_types=1);
use Dbalabka\Enumeration\Exception\EnumerationException;
use Dbalabka\Enumeration\Examples\Enum\Color;
use Dbalabka\StaticConstructorLoader\StaticConstructorLoader;
if (version_compare(PHP_VERSION, '7.4.0beta', '<')) {
trigger_error('This code requires PHP >= 7.4', E_USER_NOTICE);
return;
}
$composer = require_once(__DIR__ . '/../vendor/autoload.php');
$loader = new StaticConstructorLoader($composer);
class Square implements Serializable
{
public $color;
public function __construct(Color $color)
{
$this->color = $color;
}
public function serialize()
{
return serialize([$this->color->name()]);
}
public function unserialize($serialized)
{
[$color] = unserialize($serialized);
$this->color = Color::valueOf($color);
}
}
$square = new Square(Color::$red);
$red = Color::$red;
try {
$serialized = serialize($red);
} catch (EnumerationException $e) {
assert($e->getMessage() === 'Enum serialization is not allowed');
}
$serializedSquare = serialize($square);
$square = unserialize($serializedSquare);
assert($square->color === Color::$red);
class Dot
{
public $color;
public function __construct(Color $color)
{
$this->color = $color;
}
public function __serialize()
{
return ['color' => $this->color->name()];
}
public function __unserialize($payload)
{
$this->color = Color::valueOf($payload['color']);
}
}
$dot = new Dot(Color::$red);
$serializedDot = serialize($dot);
$dot = unserialize($serializedDot);
assert($dot->color === Color::$red);