CommonEntity.php 1.2 KB

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