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

How to define getters and modifiers in Thinkphp5

藏色散人
Release: 2021-05-11 08:59:39
forward
1896 people have browsed it

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];

    }   
}
Copy after login

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; // 例如输出“男”
Copy after login

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();
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template