Stringing together methods like that is called "chaining."
return $this;
in each method will enable chainability, since it keeps passing the instance from one method to the other, maintaining the chain.
You have to explicitly do this, since PHP functions will return NULL
by default.
So, you just need 2 more lines.
<?php
class MyClass{
function a(){
echo "F.A ";
return $this; // <== Allows chainability
}
function b(){
echo "F.B ";
return $this;
}
}
$c=new MyClass;
$c->a()->b()->b()->a();
?>
Take a look at this article by John Squibb for a further exploration of chainability in PHP.
You can do all sorts of stuff with chainability. Methods commonly involve arguments. Here's an "argument chain":
<?php
class MyClass{
private $args = array();
public function a(){
$this->args = array_merge($this->args, func_get_args());
return $this;
}
public function b(){
$this->args = array_merge($this->args, func_get_args());
return $this;
}
public function c(){
$this->args = array_merge($this->args, func_get_args());
echo "<pre>";
print_r($this->args);
echo "</pre>";
return $this;
}
}
$c=new MyClass;
$c->a("a")->b("b","c")->b(4, "cat")->a("dog", 5)->c("end")->b("no")->c("ok");
// Output:
// Array ( [0] => a [1] => b [2] => c [3] => 4 [4] => cat
// [5] => dog [6] => 5 [7] => end )
// Array ( [0] => a [1] => b [2] => c [3] => 4 [4] => cat
// [5] => dog [6] => 5 [7] => end [8] => no [9] => ok )
?>