Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
function select($select = '*')
        if( is_string($select) ) {
            $select = explode(',', $select) ;

        foreach($select as $s) {
            $s = trim($s) ;

            if($s != '') {
                $this->aSelect[] = $s ;

        return $this ;

In PHP, what is meant by return $this.

share|improve this question
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. – tdammers Aug 26 '12 at 6:37
by returning $this the function return the current object. then what is the purpose of body of the function. we can write the function somthing (){ retuen $this; } – Mehdy Mahmood Aug 26 '12 at 6:41
I took the liberty to change the title to clarify. – tdammers Aug 26 '12 at 7:02

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->whereEquals('username', $username);
$user = $query->executeSingleRow();

If each of $query's methods returns the modified query object, we can instead write this as:

$user = $database
            ->whereEquals('username', $username)

The second version is closer to how you'd write an actual SQL query, and it works without introducing the exta $query variable.

share|improve this answer

By returning $this you it makes it easier for the programmer to chain commands. Consider a car object. You could say $car->start()->forward()->left()->forward() on line if you return $this in each function.

There is actually a question about this in stack overflow which could help clarify what method chaining is:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.