| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- <?php
- namespace app\entity;
- use app\utils\ArrayUtil;
- use ReflectionClass;
- class CommonEntity
- {
- /**
- * 将 参数 实例化到 实体
- * @param array $data
- * @return CommonEntity
- */
- public static function newInstance(array $data = []): CommonEntity
- {
- if (empty($data)) {
- return new static();
- } else {
- $instance = new static();
- $data = ArrayUtil::underline2CamelArr($data);
- foreach ($instance as $ik => $iv) {
- if (isset($data[$ik])) {
- $setFunctionName = 'set' . ucfirst($ik);
- $instance->$setFunctionName($data[$ik]);
- }
- }
- return $instance;
- }
- }
- /**
- * 声明公共方法 将实体 转成数组
- * @return array
- */
- public function toArray(): array
- {
- $data = [];
- try {
- $ref = new ReflectionClass(static::class);
- foreach ($ref->getProperties() as $property) {
- $p = $ref->getProperty($property->name);
- $p->setAccessible(true);
- $data[$property->name] = $p->getValue($this);
- }
- } catch (\Exception $e) {
- }
- return $data;
- }
- }
|