属性数组 foreach ($vars as $name => $value) { $this->$name = isset($para[$name]) ? $para[$name] : $value; # 取参数中的或者默认值 } } /** * 从对象加载数据(赋值给自己的字段) * (注意: 对于自身未定义的字段直接抛弃了,所以要求所有字段都必须在model中定义好,运行时增加的字段下次加载时就会丢失) * @param array/Object $obj */ public function LoadFrom($obj) { if (func_num_args() != 1 || is_null($obj)) { # 防御: 参数数量不对 die("too many args or arg obj was null!"); } $para = is_array($obj) ? $obj : (array) $obj; # 转关联数组 $vars = get_class_vars(get_class($this)); # 后期绑定,获得实例的实际类名称=>属性数组 foreach ($vars as $name => $value) { // echoLine($name . " : " . ($this->$name != null && is_object($this->$name) ? get_class($this->$name) : "null")); if (isset($para[$name])) { if (is_a($this->$name, __CLASS__)) { # 递归加载数据 $this->$name->LoadFrom($para[$name]); } else { $this->$name = $para[$name]; # 取参数中的或者默认值 } } } return $this; } public function __toString() { # 用json_encode覆盖下toString()方法 return $this->toString(); } /** * @return 将自身数据序列化为json串. */ public function Json() { return JsonUtil::encode($this); } public function toString() { # 还没想好要不要留一个显式的toString()方法 $str = $this->Json(); return $str; } /** * @param bool $lower 是否返回小写字符串,默认值false, 返回大写字符串 * @return string 计算自身数据序列化为json串后的MD5值(大写16进制) */ public function MD5($lower = false) { $str = $this->Json(); return $lower ? md5($str) : strtoupper(md5($str)); } /** * 从json反序列化回来的时候,修正下类型. 有的时候空数组会序列化为{},再反序列化回来的时候类型就变了. */ public function fixArray() { $ref = new \ReflectionObject($this); # 建立反射对象 $properties = $ref->getProperties(); # 获取属性列表 foreach ($properties as $p) { # 遍历属性 isEditor() and $p = new \ReflectionProperty(); $attrs = $p->getAttributes("loyalsoft\ArrayType"); # 获取 "数组类型" 的注解 if (count($attrs) > 0) { $v = $p->getValue($this); if (!is_array($v)) { $v = self::ConsureArr($p->getValue($this)); # 属性值类型转换为数组 $p->setValue($this, $v); # 回写属性值到对象上 } } } } private static function ConsureArr($mix) { if (is_array($mix)) { return $mix; } return (array) $mix; } }