1--TEST-- 2json_encode() Serialization tests 3--SKIPIF-- 4<?php if (!extension_loaded("json")) print "skip"; ?> 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() 21 { 22 return $this->data; 23 } 24} 25 26class ValueSerializingTest extends SerializingTest 27{ 28 public function jsonSerialize() 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() 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--EXPECT-- 63==NonSerializingTest== 64{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}} 65{"data":["foo",1,2.3,false,null,[1,2,3],{}]} 66{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}} 67==SerializingTest== 68{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}} 69["foo",1,2.3,false,null,[1,2,3],{}] 70{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}} 71==ValueSerializingTest== 72["foo",1,2.3,false,null,[1,2,3],{}] 73["foo",1,2.3,false,null,[1,2,3],{}] 74["foo",1,2.3,false,null,[1,2,3],{}] 75==SelfSerializingTest== 76{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}} 77{"data":["foo",1,2.3,false,null,[1,2,3],{}]} 78{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}} 79 80 81