InitUpdate.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Bear
  5. * Date: 2020/6/20
  6. * Time: 下午1:45
  7. */
  8. namespace app\source\model;
  9. /**
  10. * Class InitUpdate
  11. * @package app\source\model
  12. */
  13. class InitUpdate
  14. {
  15. //设置的属性与方法映射
  16. public $fieldsMethod = [];
  17. /**
  18. * 绑定参数
  19. * @param $data
  20. * @return static
  21. */
  22. public function bind($data)
  23. {
  24. foreach ($data as $key => $value) {
  25. if (array_key_exists($key, $this->fieldsMethod)) {
  26. $this->$key = $value;
  27. }
  28. }
  29. return $this;
  30. }
  31. /**
  32. * 设置属性
  33. * @param $name
  34. * @param $value
  35. * @return $this
  36. */
  37. public function __set($name, $value)
  38. {
  39. if (is_array($value)) {
  40. $value = json_encode($value, JSON_UNESCAPED_UNICODE);
  41. }
  42. if ($this->fieldsMethod && array_key_exists($name, $this->fieldsMethod)) {
  43. if (method_exists($this, $this->fieldsMethod[$name])) {
  44. call_user_func([$this, $this->fieldsMethod[$name]], $value);
  45. } else {
  46. $this->$name = (int)$value;
  47. }
  48. }
  49. return $this;
  50. }
  51. /**
  52. * 转化为数组
  53. * @return mixed
  54. */
  55. public function toArray()
  56. {
  57. $data = [];
  58. foreach ($this as $field => $value) {
  59. if ($field == 'fieldsMethod') {
  60. continue;
  61. }
  62. $data[$field] = $value;
  63. }
  64. return $data;
  65. }
  66. }