ObjectUtil.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace addons\JoinPay\common\logic\util;
  3. class ObjectUtil
  4. {
  5. /**
  6. * 把json格式的字符串参数值赋值到对象属性中去
  7. * @param object $obj
  8. * @param string $paramJson
  9. * @param int $jsonDept
  10. */
  11. public static function fillProperties(object &$obj, string $paramJson, $jsonDept = 2){
  12. $arr = json_decode($paramJson, true, $jsonDept);
  13. if(!$arr || !is_array($arr)) {
  14. return;
  15. }
  16. $isMagicSetExist = method_exists($obj, "__set");//魔术方法是否存在
  17. foreach($arr as $key => $value) {
  18. if(! property_exists($obj, $key)){
  19. continue;
  20. }
  21. if($isMagicSetExist){
  22. $obj->$key = $value;
  23. }else{
  24. $method = "set" . ucfirst($key);
  25. if(! method_exists($obj, $method)){
  26. $method = "set";
  27. $fArr = explode("_", $key);
  28. foreach($fArr as $idx => $fName){
  29. $method .= ucfirst($fName);
  30. }
  31. }
  32. $obj->$method($value);
  33. }
  34. }
  35. }
  36. }