Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You just make sure a chainable method returns an object reference, and you can chain another method call onto the result.</p> <p>You can <code>return $this</code> as @Tim Cooper shows, or you can return a reference to another different object:</p> <pre><code>class Hand { protected $numFingers = 5; public function countFingers() { return $this-&gt;numFingers; } } class Arm { protected $hand; public function getHand() { return $this-&gt;hand; } } $n = $body-&gt;getLeftArm() // returns object of type Arm -&gt;getHand() // returns object of type Hand -&gt;countFingers(); // returns integer </code></pre> <p>The PDO example you show uses two different object types. <a href="http://php.net/manual/en/pdo.query.php" rel="nofollow noreferrer"><code>PDO::query()</code></a> instantiates and returns a <a href="http://php.net/manual/en/class.pdostatement.php" rel="nofollow noreferrer"><code>PDOStatement</code></a> object, which in turn has a <a href="http://php.net/manual/en/pdostatement.fetch.php" rel="nofollow noreferrer"><code>fetch()</code></a> method.</p> <p>This technique can also be used for a <a href="http://en.wikipedia.org/wiki/Fluent_interface#PHP" rel="nofollow noreferrer">fluent interface</a>, particularly when implementing an interface for domain-specific language. Not all method chains are fluent interfaces, though.</p> <p>See what Martin Fowler <a href="http://martinfowler.com/bliki/FluentInterface.html" rel="nofollow noreferrer">wrote about fluent interfaces</a> in 2005. He cites Eric Evans of <a href="http://rads.stackoverflow.com/amzn/click/0321125215" rel="nofollow noreferrer">Domain-Driven Design</a> fame as having come up with the idea.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload