tp5.0 的模型型別轉換問題
當用data ()->save () 的時候,data 函數的第二個參數必須設為true 的時候才能實現型別轉換
class User extends Model { protected $type = [ 'status' => 'integer', 'score' => 'float', 'birthday' => 'datetime', 'info' => 'array', ]; }
1.能型別轉換
$user = new User; $user->status = '1'; $user->score = '90.50'; $user->birthday = '2015/5/1'; $user->info = ['a'=>1,'b'=>2]; $user->save(); var_dump($user->status); // int 1 var_dump($user->score); // float 90.5; var_dump($user->birthday); // string '2015-05-01 00:00:00' var_dump($user->info);// array (size=2) 'a' => int 1 'b' => int 2
2.不能型別轉換
$user = new User; $insert ['status'] = '1'; $insert ['score'] = '90.50'; $insert ['birthday'] = '2015/5/1'; $insert ['info'] = ['a'=>1,'b'=>2]; $user->data($insert)->save(); var_dump($user->status); // string '1'; var_dump($user->score); // string '90.5'; var_dump($user->birthday); // string '2015/5/1' var_dump($user->info);// array (size=2) 'a' => int 1 'b' => int 2
3.能型別轉換
$user->data($insert, true)->save();
Model.php ...... public function data($data, $value = null) { if (is_string($data)) { $this->data[$data] = $value; } else { // 清空数据 $this->data = []; if (is_object($data)) { $data = get_object_vars($data); } if (true === $value) { // 数据对象赋值 foreach ($data as $key => $value) { $this->setAttr($key, $value, $data); } } else { $this->data = $data; } } return $this; } .......
只有經過setAttr 函式才會進行型別轉換
本文來自ThinkPHP框架技術文章欄:http://www.php.cn/phpkj/ thinkphp/
以上是tp5.0 的模型類型轉換問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!