// Little known PHP features: method chaining, enabling you to call methods the short way

Since PHP5, methods can return objects (including $this). This enables you to chain the method calls after preparing your class by returning the object itself. Therefore, “Method chaining” may save you e.g. much copy & paste or chars to type, reducing typing time for dozens of $obj->method() calls.

<?php
 
//common way
class foo {	
    public function one() {
        echo "one ";
    }
    public function two() {
        echo "two ";
    }
    public function three() {
        echo "three\n\n";
    }
}
$object = new foo();
$object->one();
$object->two();
$object->three();
 
 
//with method chaining (note the "return $this;")
class bar {	
    public function one() {
        echo "one ";
        return $this;
    }
    public function two() {
        echo "two ";
        return $this;
    }
    public function three() {
        echo "three\n\n";
        return $this;
    }
}
$object = new bar();
$object->one()
       ->two()
       ->three();
?>

I did not made any performance measurements right now… so I can't say if method chaining is faster/slower in common environments or not. And to be honest, I don't use method chaining for myself:

  • You simply can't see if a class supports method chaining without trying it or looking at its source.
  • The need for all these return $this; within the class methods.
  • IMHO, both reasons are leading to inconsistent coding styles and behaviors in real world applications containing 3rd party classes.

Comments

No. 1 @ 2013/05/15 17:24

Hi, To return the class instance in the static method (to chain it), you can use: return new self; . Here is an example: http://coursesweb.net/php-mysql/chaining-static-public-class-methods-php_cs

Leave a comment…




F K Y W A
  • E-Mail address will not be published.
  • Formatting:
    //italic//  __underlined__
    **bold**  ''preformatted''
  • Links:
    [[http://example.com]]
    [[http://example.com|Link Text]]
  • Quotation:
    > This is a quote. Don't forget the space in front of the text: "> "
  • Code:
    <code>This is unspecific source code</code>
    <code [lang]>This is specifc [lang] code</code>
    <code php><?php echo 'example'; ?></code>
    Available: html, css, javascript, bash, cpp, …
  • Lists:
    Indent your text by two spaces and use a * for
    each unordered list item or a - for ordered ones.
I'm no native speaker (English)
Please let me know if you find any errors (I want to improve my English skills). Thank you!
QR Code: URL of current page
QR Code: URL of current page 2012:01:11:php-method-chaining (generated for current page)