Home  >  Article  >  PHP Framework  >  How to define getters and modifiers in Thinkphp5

How to define getters and modifiers in Thinkphp5

藏色散人
藏色散人forward
2021-05-10 15:25:131868browse

The following tutorial column will introduce to you how to define getters and modifiers in Thinkphp5. I hope it will be helpful to friends in need! Defining getters and modifiers in Thinkphp5

One getter: The function of the getter is to automatically process the field value after getting the data. In fact, it will The data obtained from the database becomes another form we want, Then the getter is the tool for conversion

The getter is usually defined in the model, that If the table needs a getter, it 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 camel case nomenclature is a fixed definition format. The Sex in the middle is generally the field name in our database. In the method The meaning of the definition is that if the sex field in the database = 0, then the displayed value is 'female',

If the sex field in the database = 1, then the displayed value is 'male'

In the controller, we use the User model to perform 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 pass this method Convert data,

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();

Related recommendations:

The latest 10 thinkphp video tutorials

The above is the detailed content of How to define getters and modifiers in Thinkphp5. 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