There are many scenarios in which one might want to return $this
from a function, but the most popular one is 'method chaining'.
For example, in an SQL abstraction layer, you may have an object that represents a query, and then call a series of methods on it to extend it. Consider the following code:
$query = $database->select();
$query->from('users');
$query->whereEquals('username', $username);
$query->orderBy('username');
$query->limit(1);
$user = $query->executeSingleRow();
If each of $query
's methods returns the modified query object, we can instead write this as:
$user = $database
->select()
->from('users')
->whereEquals('username', $username)
->orderBy('username')
->limit(1)
->executeSingleRow();
The second version is closer to how you'd write an actual SQL query, and it works without introducing the exta $query
variable.
return
means what it always means: return a value from a function.$this
is the current object, usually the object through which the current member function was called.