Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.
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

2 Answers 2

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.

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: http://stackoverflow.com/questions/3724112/php-method-chaining

share|improve this answer

Your Answer

 
discard

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.