CommonEntity.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace app\entity;
  3. use app\utils\ArrayUtil;
  4. use ReflectionClass;
  5. class CommonEntity
  6. {
  7. /**
  8. * 将 参数 实例化到 实体
  9. * @param array $data
  10. * @return CommonEntity
  11. */
  12. public static function newInstance(array $data = []): CommonEntity
  13. {
  14. if (empty($data)) {
  15. return new static();
  16. } else {
  17. $instance = new static();
  18. $data = ArrayUtil::underline2CamelArr($data);
  19. foreach ($instance as $ik => $iv) {
  20. if (isset($data[$ik])) {
  21. $setFunctionName = 'set' . ucfirst($ik);
  22. $instance->$setFunctionName($data[$ik]);
  23. }
  24. }
  25. return $instance;
  26. }
  27. }
  28. /**
  29. * 声明公共方法 将实体 转成数组
  30. * @return array
  31. */
  32. public function toArray(): array
  33. {
  34. $data = [];
  35. try {
  36. $ref = new ReflectionClass(static::class);
  37. foreach ($ref->getProperties() as $property) {
  38. $p = $ref->getProperty($property->name);
  39. $p->setAccessible(true);
  40. $data[$property->name] = $p->getValue($this);
  41. }
  42. } catch (\Exception $e) {
  43. }
  44. return $data;
  45. }
  46. }