Arrayable.php 540 B

12345678910111213141516171819202122232425262728
  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. public function toArray(): array
  12. {
  13. $result = [];
  14. foreach ((new ReflectionClass($this))->getProperties() as $item) {
  15. $k = $item->getName();
  16. $method = 'get'.Str::studly($k);
  17. $result[Str::snake($k)] = method_exists($this, $method) ? $this->{$method}() : $this->{$k};
  18. }
  19. return $result;
  20. }
  21. }