xref: /PHP-8.0/tests/classes/serialize_001.phpt (revision f8d79582)
1--TEST--
2ZE2 Serializable
3--FILE--
4<?php
5
6class Test implements Serializable
7{
8    public $data;
9
10    function __construct($data)
11    {
12        echo __METHOD__ . "($data)\n";
13        $this->data = $data;
14    }
15
16    function serialize()
17    {
18        echo __METHOD__ . "({$this->data})\n";
19        return $this->data;
20    }
21
22    function unserialize($serialized)
23    {
24        echo __METHOD__ . "($serialized)\n";
25        $this->data = $serialized;
26        var_dump($this);
27    }
28}
29
30$tests = array('String', NULL, 42, false);
31
32foreach($tests as $data)
33{
34    try
35    {
36        echo "==========\n";
37        var_dump($data);
38        $ser = serialize(new Test($data));
39        var_dump(unserialize($ser));
40    }
41    catch(Exception $e)
42    {
43        echo 'Exception: ' . $e->getMessage() . "\n";
44    }
45}
46
47?>
48--EXPECTF--
49==========
50string(6) "String"
51Test::__construct(String)
52Test::serialize(String)
53Test::unserialize(String)
54object(Test)#%d (1) {
55  ["data"]=>
56  string(6) "String"
57}
58object(Test)#%d (1) {
59  ["data"]=>
60  string(6) "String"
61}
62==========
63NULL
64Test::__construct()
65Test::serialize()
66NULL
67==========
68int(42)
69Test::__construct(42)
70Test::serialize(42)
71Exception: Test::serialize() must return a string or NULL
72==========
73bool(false)
74Test::__construct()
75Test::serialize()
76Exception: Test::serialize() must return a string or NULL
77