Arrayable.php 633 B

1234567891011121314151617181920212223242526272829303132
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Supports\Traits;
  4. use ReflectionClass;
  5. use Yansongda\Supports\Str;
  6. trait Arrayable
  7. {
  8. /**
  9. * toArray.
  10. *
  11. * @author yansongda <me@yansongda.cn>
  12. *
  13. * @throws \ReflectionException
  14. */
  15. public function toArray(): array
  16. {
  17. $result = [];
  18. foreach ((new ReflectionClass($this))->getProperties() as $item) {
  19. $k = $item->getName();
  20. $method = 'get'.Str::studly($k);
  21. $result[Str::snake($k)] = method_exists($this, $method) ? $this->{$method}() : $this->{$k};
  22. }
  23. return $result;
  24. }
  25. }