thinkphp5 method of calling model
ThinkPHP5.0 model calling
1. Model classes can be called statically or instantiated, for example:
Recommended learning: thinkphp5
// 静态调用 $user = User::get(1); $user->name = 'thinkphp'; $user->save(); // 实例化模型 $user = new User; $user->name= 'thinkphp'; $user->save(); // 使用 Loader 类实例化(单例) $user = Loader::model('User'); // 或者使用助手函数`model` $user = model('User'); $user->name= 'thinkphp'; $user->save();
2. Model initialization
1. The model also supports initialization. Different from the initialization of the controller, the initialization of the model is to override the initialize of the Model, as follows
namespace app\index\model; use think\Model; class Index extends Model { //自定义初始化 protected function initialize() { //需要调用`Model`的`initialize`方法 parent::initialize(); //TODO:自定义的初始化 } }
2. You can also use the static init method. It should be noted that init is only executed when it is instantiated for the first time, and you need to pay attention to the specifications of static calls in the method, as follows
namespace app\index\model; use think\Model; class Index extends Model { //自定义初始化 protected static function init() { //TODO:自定义的初始化 } }
The above is the detailed content of How to call the model in thinkphp5. For more information, please follow other related articles on the PHP Chinese website!