What does "return $this" mean?
$this
means the current object, the one the method is currently being run on. By returning $this
a reference to the object the method is working gets sent back to the calling function.
So anyone doing
$foo2 = $foo->SetOptions($bar);
$foo2 now refers to $foo also.
you just can create a function chain
class My_class
{
public function method1($param)
{
/*
* logic here
*/
return $this;
}
public function method2($param)
{
/*
* logic here
*/
return $this;
}
public function method3($param)
{
/*
* logic here
*/
return $this;
}
}
so you can use this
My_class obj = new My_class();
$return = obj->method1($param)->method2($param)->method3($param);
This way of coding is called fluent interface. return $this
returns the current object, so you can write code like this:
$object
->function1()
->function2()
->function3()
;
instead of:
$object->function1();
$object->function2();
$object->function3();
This will return the instance this method is called on. This usually done for achieving fluent interfaces so you can call stuff like:
CoolClass::factory('hello')->setOptions(array('coolness' => 5))->sayHello();
Where both setOptions
and sayHello
would be called on the same object.