1. Introduction
ThinkPHP3.2.0 is a popular PHP web framework. Its setInc method is widely used to increment a field value of a record in database. In this article, we will give a comprehensive analysis of its source code.
2. Overview of setInc method
The setInc method is defined in the Model class of ThinkPHP. It is used to increment a field value of a record in database by a specified number.
public function setInc($field,$where = '',$step = 1)
{
return $this->setField($field,array($field->exp("@{$field}+{$step}")),$where);
}
2.1 Parameters of setInc method
The setInc method takes three parameters:
$field: the field name to be incremented
$where (optional): the condition of selecting records to be incremented
$step (optional): the increment step, default is 1
2.2 Return value of setInc method
The setInc method returns the number of affected rows in database.
3. Analysis of setInc source code
Let's take a closer look at the source code of setInc method.
public function setInc($field,$where = '',$step = 1)
{
return $this->setField($field,array($field->exp("@{$field}+{$step}")),$where);
}
3.1 Call to setField method
The setInc method internally calls the setField method of Model class. This is because the logic of updating a field value is already implemented in the setField method.
3.2 Argument of setField method
The first argument of setField method is $field, which is the same as the first argument of setInc method.
3.3 Value expression of setField method
The second argument of setField method is an array with an element.
array($field->exp("@{$field}+{$step}"))
The value expression is created by concatenating the field name, an addition operator and the increment step.
The exp method of Field class is used to convert the value expression into a string.
3.4 Condition of setField method
The third argument of setField method is $where, which is the same as the second argument of setInc method.
3.5 Return value of setInc method
The return value of setInc method is the same as the return value of setField method, which is the number of affected rows in database.
4. Conclusion
The setInc method of ThinkPHP is a simple but powerful method for incrementing a field value of a record in database. Its source code is concise and easy to understand.