|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2020-08-13 13:15 UTC] fodor dot laszlo at gmail dot com
Description: ------------ It would be great if stdClass would implement JsonSerializable for multiple reasons. First of all, since the interface has been introduced a lot of methods are expecting JsonSerializable as a parameter to work with by type-hinting the parameter. And sometimes these methods should work properly with an array as well. If stdClass would implement JsonSerializable interface a simple (object) casting would be enough to pass an array to such method. Another reason is testing. Currently I need to set up a Mock object to test a method what expects a JsonSerializable. Instead I could just use a simple stdClass with some dummy data in it PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 21:00:01 2025 UTC |
> Otherwise it could be literally used with anything and would just generate an empty json object. The default JSON serialization behavior is to just serialize the properties. If you have a class class Point { public int $x; public int $y; public int $z; } then the natural serialization for that is {"x": 0, "y": 1, "z": 2}, which is what you get by default -- you do need to and should not implement JsonSerializable in that case. You should treat any value under the assumption that it can be serialized (but check for encoding errors). (In fact, a reasonable use of JsonSerializable would be to make the implementation throw unconditionally if your object is not serializable -- the fact that it implements JsonSerializable clearly doesn't indicate serializability in that case.)