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.

  • 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.

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

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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