1

This is something that I have been really curious about. I have tried to find the answer myself but I can't exactly think what to google. So first off, I am used to doing a regular query method either like this (when escaping):

$Database->query($sql)

or if using prepared statements like this:

$Database->statement($sql, array('ss', $val1, $val2))

However when reading through the source code of a project, I found this:

$id = DB::SQL()
                ->select("postId")
                ->from("post")
                ->where("conversationId=:conversationId")->bind(":conversationId", $conversation["conversationId"])
                ->orderBy("time DESC")
                ->limit(1)
                ->exec()
                ->result();

Now I know this is PDO, and also a random example however since I read this I've been wondering how this is done. If someone would be kind enough to explain then I'd really appreciate it.

user3481788
  • 161
  • 10
  • 3
    Are you asking how "method chaining" is implemented? Simple, have each method return the same object it was called with. If it's part of a class, then `return $this;`. – gen_Eric Oct 16 '14 at 17:10
  • this is what i call method chaining ..;) – Avinash Babu Oct 16 '14 at 17:12
  • PDO in PHP does not support method chaining, nor does the given example look like PHP's PDO interface – dbf Oct 16 '14 at 17:50

1 Answers1

1

The method you have done here is method chaining.

A simple example from here.

<?php

class fakeString

{
private $str;
function __construct()
{
    $this->str = "";
}

function addA()
{
    $this->str .= "a";
    return $this;
}

function addB()
{
    $this->str .= "b";
    return $this;
}

function getStr()
{
    return $this->str;
}
}


$a = new fakeString();

echo $a->addA()->addB()->getStr(); //outputs ab
Community
  • 1
  • 1
Avinash Babu
  • 6,171
  • 3
  • 21
  • 26