xref: /PHP-8.1/ext/json/tests/serialize.phpt (revision 5beba0b0)
1--TEST--
2json_encode() Serialization tests
3--INI--
4serialize_precision=-1
5--FILE--
6<?php
7
8class NonSerializingTest
9{
10    public $data;
11
12    public function __construct($data)
13    {
14        $this->data = $data;
15    }
16}
17
18class SerializingTest extends NonSerializingTest implements JsonSerializable
19{
20    public function jsonSerialize(): mixed
21    {
22        return $this->data;
23    }
24}
25
26class ValueSerializingTest extends SerializingTest
27{
28    public function jsonSerialize(): mixed
29    {
30        return array_values(is_array($this->data) ? $this->data : get_object_vars($this->data));
31    }
32}
33
34class SelfSerializingTest extends SerializingTest
35{
36    public function jsonSerialize(): mixed
37    {
38        return $this;
39    }
40}
41
42$adata = array(
43    'str'	=> 'foo',
44    'int'	=> 1,
45    'float'	=> 2.3,
46    'bool'	=> false,
47    'nil'	=> null,
48    'arr'	=> array(1,2,3),
49    'obj'	=> new StdClass,
50);
51
52$ndata = array_values($adata);
53
54$odata = (object)$adata;
55
56foreach(array('NonSerializingTest','SerializingTest','ValueSerializingTest','SelfSerializingTest') as $class) {
57    echo "==$class==\n";
58    echo json_encode(new $class($adata)), "\n";
59    echo json_encode(new $class($ndata)), "\n";
60    echo json_encode(new $class($odata)), "\n";
61}
62?>
63--EXPECT--
64==NonSerializingTest==
65{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
66{"data":["foo",1,2.3,false,null,[1,2,3],{}]}
67{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
68==SerializingTest==
69{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}
70["foo",1,2.3,false,null,[1,2,3],{}]
71{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}
72==ValueSerializingTest==
73["foo",1,2.3,false,null,[1,2,3],{}]
74["foo",1,2.3,false,null,[1,2,3],{}]
75["foo",1,2.3,false,null,[1,2,3],{}]
76==SelfSerializingTest==
77{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
78{"data":["foo",1,2.3,false,null,[1,2,3],{}]}
79{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
80