New Website

I've made a new website, as lynx.io is dead. You can find it here: http://macr.ae/—it's similar in format to lynx.io, but has better articles, and they're all written by me.

JavaScript disabled

While it will still mostly work, a lot of this site's functionality relies on JavaScript - please enable it for the best experience.

Method Chaining in PHP

Method chaining allows for shorter and cleaner code, and in this article I will explain how it is possible in PHP. The best way to explain method chaining is to show you an example of it:

Without method chaining:

$abc = new Site();
$abc->add_info('title', 'Hello world!');
$abc->add_info('body', $body);
$abc->add_info('footer', 'Copyright Callum Macrae');

With method chaining:

$abc = new Site();
$abc->add_info('title', 'Hello world!')
    ->add_info('body', $body)
    ->add_info('footer', 'Copyright Callum Macrae');

Or slightly more obvious:

$abc = new Site();
$abc->add_info('title', 'Hello world!')->add_info('body', $body)->add_info('footer', 'Copyright Callum Macrae');

As you can see, the code is a lot cleaner with method chaining. Method chaining is quite commonly used in other languages, such as JavaScript. The following code excerpt is off the Node.js homepage:

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");

Method chaining! It's clearer when displayed without the parameters:

http.createServer(function)
    .listen(port, ip);

 

You can do it by returning $this at the end of your methods. For example:

<?php

class EchoIt {
    private $text = array();
    public function add($text) {
        $this->text[] = $text;
        return $this;
    }

    public function out() {
        echo join($this->text, ' ') . PHP_EOL;
        $this->text = array();
        return $this;
    }
}

$text = new EchoIt;
$text->add('Hello')->add('world')->out()
    ->add('This')->add('is')->add('a')->add('test')->out();

This will output:

Hello world
This is a test

 

It's all fairly simple. One of the great things about this example is that PHP passes objects by reference, so the following code would do the same thing:

$text->add('Hello')->add('world');
$text->out();
$text->add('This')->add('is')->add('a')->add('test');
$text->out();

About Callum Macrae:

Callum Macrae is the founder of lynx.io and a JavaScript developer from the United Kingdom. He is currently writing his first book, to be published by O'Reilly Media.

You can view more articles by this author here.

Tags: php method chaining oop

Comments

No comments; leave one below.

says:

Add comment

 

You can use markdown in comments (press "m" for a cheatsheet).

Enable JavaScript to post a comment

Markdown Cheat Sheet

# This is an <h1> tag
## This an <h2> tag
###### This is an <h6> tag

Inline markup: _this text is italic_, **this is bold**, and `code()`.

[Link text](link URL "Optional title")
[Google](http://google.com/ "Google!")

![Alt text](image URL)

![This is a fish](images/fish.jpg)

1. Ordered list item 1
2. Ordered list item 2

* Unordered list item 1
* Unordered list item 2
* Item 2a
* Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:

----

> This is a blockquote

This is an <h1> tag

This an <h2> tag

This is an <h6> tag

Inline markup: this text is italic, this is bold, and code().

Link text Google

This is a fish

  1. Ordered list item 1
  2. Ordered list item 2
  • Unordered list item 1
  • Unordered list item 2
    • Item 2a
    • Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:


This is a blockquote

Toggle MarkDown / HTML (t), full reference or close this