Php – the purpose of returning $this in PHP

PHP

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.

Best Answer

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.

Related Topic