JsonOb.php 997 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace UCore\Helper;
  3. /**
  4. * 应对json的对象默认值是[]
  5. *
  6. */
  7. class JsonOb implements \JsonSerializable
  8. {
  9. public function __construct(private $data=[])
  10. {
  11. }
  12. /**
  13. * 默认对象
  14. * @param $oba
  15. * @return JsonOb|array|object
  16. */
  17. static public function deObject($oba)
  18. {
  19. if (is_object($oba)) {
  20. return $oba;
  21. } elseif (is_array($oba)) {
  22. if ($oba === []) {
  23. return new JsonOb();
  24. }
  25. return new JsonOb($oba);
  26. } else {
  27. return new JsonOb();
  28. }
  29. }
  30. public function isEmpty()
  31. {
  32. return empty($this->data);
  33. }
  34. public function __toString(): string
  35. {
  36. if($this->data){
  37. return json_encode($this->data);
  38. }
  39. return '{}';
  40. }
  41. public function jsonSerialize()
  42. {
  43. if($this->data){
  44. return $this->data;
  45. }
  46. return new \stdClass();
  47. }
  48. }