Skip to content


Method Chaining in PHP5

Chaining method calls can help shorten the amount of code you have to write while accomplishing the same programatic goals.

Let’s say, you have a class that needs to have some data set to it before you can start applying methods. A traditional approach may look like this.

class A {
    private $data;
    public function setData($data) {
        $this->data = $data;
        return void;
    }
 
    public function validateData() {
        if(is_array($data)) {
            return true;
        }
        return false;
    }
}
 
//Would be called like...
$form = new A();
$form->setData($_REQUEST);
if($form->validateData()) {
    echo "valid data";
}

Although, this is a very basic example utilizing method chaining in PHP5 we can also write the class like this…

class A {
    private $data;
    public function setData($data) {
        $this->data = $data;
        return $this;
    }
 
    public function validateData() {
        if(is_array($data)) {
            return true;
        }
        return false;
    }
}
 
//Would be called like...
$form = new A();
if($form->setData($_REQUEST)->validateData()) {
    echo "valid data";
}

You aren’t limited to one method either, you can chain as many methods as you need as long as the method you are calling returns a reference to itself.

Posted in PHP.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.