This article will introduce you to a tutorial on comparing the four methods of Thinkphp Object Instantiation. I hope this tutorial will help you. This article will introduce you to a tutorial on comparing the four methods of Thinkphp Object Instantiation. I hope this tutorial will help you.
Script ec (2); script
Thinkphp has four different methods for instantiating objects: new method, D method, M method, and empty model method. commonly used methods are d method and m method. This article is mostly about the official manual and I will summarize it myself.
New Method
The new method is the best way to understand it. It is a common instantiation class. The parameters are optional, including the table name, table prefix, and database connection information. In most cases, no parameter is required.
New \ Home \ Model \ NewModel ('new', 'Think _ ', 'db _ config ');
D Method
The D Method Thingkphp (TP) system provides a shortcut for instantiating classes. Through the D method, we can quickly instantiate a class and use it.
// Instantiate the Model
$ User = D ('user ');
// Equivalent
$ User = new \ Home \ Model \ UserModel ();
// Perform specific data operations
$ User-> select ();
If the \ Home \ Model \ UserModel class does not exist, function D will try to instantiate the \ Common \ Model \ UserModel class under the Public module, if it does not exist, the system's \ Think \ Model base class will be instantiated, which is worth noting.
M METHOD
The D method is used to instantiate a model class. If you only perform basic CURD operations on the data table, use the M method to instantiate the model class, because you do not need to load a specific model class, the performance will be higher.
// Use the m method for instantiation
$ User = M ('user ');
// Equivalent to the following
$ User = new \ Think \ Model ('user ');
// Execute other data operations $ User-> select ();
If your model class has its own business logic, the M method is not supported. Even if you have defined a specific model class, the M method will be ignored directly during instantiation.
Instantiate an empty model class
If you only use native SQL queries, You Can instantiate an empty model class without using additional model classes.
// Instantiate an empty Model
$ Model = new Model ();
// Or the M shortcut is equivalent.
$ Model = M ();
// Perform native SQL queries
$ Model-> query ('select * FROM think_user WHERE status = 1 ');
Summary
We often use the D and M methods in the instantiation process. The difference between the two methods is that the M method instantiation model does not require users to define model classes for each data table, if the defined model class is not found in the D method, the M method is automatically called. The M method directly ignores the custom model class.