Home  >  Article  >  PHP Framework  >  Detailed explanation of how to define getters and modifiers in Tp5

Detailed explanation of how to define getters and modifiers in Tp5

藏色散人
藏色散人forward
2021-09-02 17:27:082482browse

thinkphp The framework tutorial column will introduce you to a detailed explanation of how to define getters and modifiers in thinkphp5. I hope it will be helpful to friends in need!

Detailed explanation of how to define getters and modifiers in Tp5

One getter:The function of the getter is to automatically process the field value of the data after getting it. In fact, it is to turn the data obtained in the database into Another form we want to get,

Then the getter is the tool to convert from it

The getter is usually defined in In the model, the table that requires a getter is defined in the model of the corresponding table

<?php
namespace app\index\model;

use think\Model;

class User extends Model{

    设置获取器
    public function getSexAttr($value){

        $sex=[
            0=>&#39;女&#39;,
            1=>&#39;男&#39;
        ];

        return $sex[$value];
    }
    设置修改器
    public function setSexAttr($value){
        $sex=[
            &#39;男&#39;=>1,
            &#39;女&#39;=>0
        ];

        return $sex[$value];

    }   
}

getSexAttr The camel case nomenclature is a fixed definition format, and the Sex in the middle is generally the field name and method in our database The definition in means that if the sex field in the database = 0, then the image will be 'female'. If the sex field in the database = 1, then the displayed value will be 'male'

In the controller we use User model performs database query operations

$user = User::get(1);
echo $user->sex; // 例如输出“男”

setSexAttr camel case naming method defines the modifier, with the same Sex as the field name. When we modify or insert new data, the data will be converted through this method.
In the above method, when we insert the field value ='male' into the database sex field, the actual data stored in the database is '1'

$user=new User();
         $user->name=&#39;名字&#39;;
        $user->sex=&#39;男&#39;;
        $user->age=20;
        $res= $user->save();

The above is the detailed content of Detailed explanation of how to define getters and modifiers in Tp5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete