Hi,
I am using PHP5, and heard of a new featured in object-oriented approach, called method chaining.
Does any one know what it is?
I want to know how to implement method chaining using PHP5 with object-oriented approach.
Thanks
Hi,
I am using PHP5, and heard of a new featured in object-oriented approach, called method chaining.
Does any one know what it is?
I want to know how to implement method chaining using PHP5 with object-oriented approach.
Thanks
Its rather simple really, you have a series of mutator methods that all returns the original (or other) objects, that way you can keep calling functions.
<?php
class fakeString
{
private $str;
function __construct()
{
$this->str = "";
}
function addA()
{
$this->str .= "a";
return $this;
}
function addB()
{
$this->str .= "b";
return $this;
}
function getStr()
{
return $this->str;
}
}
$a = new fakeString();
echo $a->addA()->addB()->getStr();
This outputs "ab"
Method chaining means that you can chain method calls like this:
$object->method1()->method2()->method3()
This means that method1() needs to return an object, and method2() is given the result of method2(). Method2() then passes the return value to method3().
Good article: http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
Basically, you take an object:
$obj = new ObjectWithChainableMethods();
Call a method that effectively does a return $this;
at the end:
$obj->doSomething();
Since it returns the same object, or rather, a reference to the same object, you can continue calling methods of the same class off the return value, like so:
$obj->doSomething()->doSomethingElse();
That's it, really. Two important things:
As you note, it's PHP 5 only. It won't work properly in PHP 4 because it returns objects by value and that means you're calling methods on different copies of an object, which would break your code.
Again, you need to return the object in your chainable methods:
public function doSomething() {
// Do stuff
return $this;
}
public function doSomethingElse() {
// Do more stuff
return $this;
}