PHP method chaining

Jul 31 2010

Method chaining is a technique that adds class methods one on top the other. It’s commonly used in jQuery and models in PHP frameworks.

The whole “magic” behind object chaining is made with a single line – “return $this” which is added in each method you wish to chain.

So, in order to get this behavior in PHP:

$human = new Human;
$human->setName('Haris')
      ->setAge(30)
      ->setSex('male')
      ->display();

you have to define class(es) like this:

class Human {

    protected $_name;
    protected $_age;
    protected $_sex;

    public function setName($name) {
        $this->_name = $name;
        return $this;
    }

    public function setAge($age) {
        $this->_age = $age;
        return $this;
    }

    public function setSex($sex) {
        $this->_sex = $sex;
        return $this;
    }

    public function display() {
        printf('Hi, I\'m %s. I\'m %d years old, and I\'m %s!',
            $this->_name,
            $this->_age,
            $this->_sex
        );
    }

}

class Man extends Human {
    protected $_sex = 'male';
}

class Woman extends Human {
    protected $_sex = 'female';
}

Now compare the methods called with method chaining and the old fashioned way

$woman = new Woman;
$woman->setName('Jane')
      ->setAge(27)
      ->display();

$woman = new Woman;
$woman->setName('Jane');
$woman->setAge(27);
$woman->display();

// Hi, I'm Jane. I'm 27 years old, and I'm female!

Comments Off

Comments are closed at this time.

Performance Optimization WordPress Plugins by W3 EDGE