MsgpackUtil.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace loyalsoft;
  3. /**
  4. * Msgpack转换工具
  5. * @author gwang
  6. * @version: <br/>
  7. * v1.0.0 file copy and created. gwang 2024.9.28 <br/>
  8. */
  9. class MsgpackUtil {
  10. public $name;
  11. public function Test(){
  12. var_dump(nameof($this));
  13. var_dump(nameof( $this->name));
  14. }
  15. /**
  16. * obj -> bytes
  17. * @param mixed $obj
  18. * @return string
  19. */
  20. public static function encode($obj) {
  21. $bytes = \msgpack_pack($obj);
  22. return $bytes;
  23. }
  24. /**
  25. * bytes -> obj
  26. * @param type $string
  27. * @return obj
  28. */
  29. public static function decode($string) {
  30. $obj = \msgpack_unpack( $string);
  31. return $obj;
  32. }
  33. /**
  34. * 研发中..., 想着直接一步到位, 反序列化成目标类型的对象. -by gwang 2017年8月8日 09:49:09
  35. * @param string $str json字符串
  36. * @param mixed $tarType 目标类型
  37. * @return obj
  38. */
  39. public static function decode2Object($str, $tarType = null) {
  40. $obj = self::decode($str);
  41. if ($tarType != null) {
  42. $c = 'stdClass';
  43. if (is_string($tarType)) { # 类型名称
  44. $c = $tarType;
  45. } else if (is_object($tarType)) { # 目标类型的对象,数据还不能处理
  46. $c = get_class($tarType);
  47. }
  48. $desObj = new $c;
  49. CommUtil::loadObject($obj, $desObj); # 装到目标类型的箱子中
  50. $obj = $desObj;
  51. }
  52. return $obj;
  53. }
  54. }