$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; } /** * 将实体属性(驼峰命名)转换为下划线命名的数组 * 用于数据库写入 * @return array */ public function toUnderlineArray(): array { $result = []; $camelArray = $this->toArray(); // 先获取驼峰格式的数组 foreach ($camelArray as $key => $value) { if (is_null($value)) { continue; } // 将驼峰键名转为下划线格式 $underlineKey = $this->camelToUnderline($key); $result[$underlineKey] = $value; } return $result; } /** * 驼峰命名转下划线命名 * @param string $camel * @return string */ private function camelToUnderline(string $camel): string { // 处理连续大写字母(如 "userID" 转 "user_id") $camel = preg_replace('/([A-Z]+)([A-Z][a-z])/', '$1_$2', $camel); // 将大写字母前添加下划线并转为小写 return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $camel)); } }