views:

71

answers:

2

I am a self thought hobby programmer and therefore don't have the fundamentals always down the way you professionals do. So please excuse me if this is basic.

What is the purpose or benefit of return'ing $this when setting vars in the model. I have seen this done in other places too but cant figure this out.

Sample code:

public function setAlias($Alias){
    $this->_Alias = (string) $Alias;
    return $this;
}

public function getAlias(){
    return $this->_Alias;
}
+10  A: 

It allows you to do method chaining. For example,

$object = new Object();
$object->setAttribute1("value")->setAttribute2("value")
Seph
Learned something thank you.http://en.wikipedia.org/wiki/Method_chaining
TaMeR
Also known as a "Fluent Interface": http://en.wikipedia.org/wiki/Fluent_interface.
smack0007
@smack0007 As you can see in the article you linked, mere Method Chaining does not already constitute a Fluent Interface. Fluent Interfaces are for creating internal DSLs. The best example being `Zend_Db_Select`.
Gordon
@Gordon So you're right.
smack0007
+2  A: 

It allows method chaining:

$someObj->method1()->method2();
Ignacio Vazquez-Abrams