json_encode.phpt 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. --TEST--
  2. Enum in json_encode
  3. --FILE--
  4. <?php
  5. enum Foo {
  6. case Bar;
  7. }
  8. enum IntFoo: int {
  9. case Bar = 0;
  10. }
  11. enum StringFoo: string {
  12. case Bar = 'Bar';
  13. }
  14. enum CustomFoo implements JsonSerializable {
  15. case Bar;
  16. public function jsonSerialize(): mixed {
  17. return 'Custom ' . $this->name;
  18. }
  19. }
  20. function test($value) {
  21. var_dump(json_encode($value));
  22. echo json_last_error_msg() . "\n";
  23. if (json_last_error() !== JSON_ERROR_NONE) {
  24. echo json_last_error() . ' === ' . JSON_ERROR_NON_BACKED_ENUM . ":\n";
  25. var_dump(json_last_error() === JSON_ERROR_NON_BACKED_ENUM);
  26. }
  27. try {
  28. var_dump(json_encode($value, JSON_THROW_ON_ERROR));
  29. echo json_last_error_msg() . "\n";
  30. } catch (Exception $e) {
  31. echo get_class($e) . ': ' . $e->getMessage() . "\n";
  32. }
  33. }
  34. test(Foo::Bar);
  35. test(IntFoo::Bar);
  36. test(StringFoo::Bar);
  37. test(CustomFoo::Bar);
  38. ?>
  39. --EXPECT--
  40. bool(false)
  41. Non-backed enums have no default serialization
  42. 11 === 11:
  43. bool(true)
  44. JsonException: Non-backed enums have no default serialization
  45. string(1) "0"
  46. No error
  47. string(1) "0"
  48. No error
  49. string(5) ""Bar""
  50. No error
  51. string(5) ""Bar""
  52. No error
  53. string(12) ""Custom Bar""
  54. No error
  55. string(12) ""Custom Bar""
  56. No error