3

I'm a n00b tying to get my head around the operator syntax. I understand it's called the object operator and I can see how it's used (Where do we use the object operator "->" in PHP?) by itself.

I'm trying to learn what the purpose is when they are strung together like in this snippet (e.g. "switch($this->request->param('id')):

here's a snippet of code from a site using Kohana:

public function action_list()
{
    $connections = ORM::factory('Connection')
        ->with('property')
        ->with('inviter');
    switch ($this->request->param('id')) {
    // more code...
        }
    }
Community
  • 1
  • 1
DBWeinstein
  • 8,605
  • 31
  • 73
  • 118

2 Answers2

4

It's called "method chaining". It allows you to apply more then one method, and thus do more then one thing, in one call. It's sort of the OOP equivalent of nesting functions.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Thanks! So, in my simple world, are you saying it's a way of calling more than one method on the same argument? I guess the are completed one at a time, in order? Do the methods have to be related to each other in some way? I guess I have lots of questions. is there a good resource on this? – DBWeinstein Mar 03 '13 at 17:46
  • It allows you to be very flexible in how you construct, well, lots of things including objects, queries, etc. Typically the methods are related (they're all related to constructing a query, filtering, etc). But technically they don't have to be related. You'll find lots of tutorials on how to chain methods but few explaining why. But if you use a framework that takes advantage of it, it won't take you long to figure out when and why it's handy. – John Conde Mar 03 '13 at 17:49
  • The method returns the object it belongs to, so you can just call another one on top of it. – DanMan Mar 03 '13 at 17:51
0

It's often referred to as chaining. When a method returns an object, you can call another method on that returned object. Consider something like this:

class A {
    public $numbers = 0;
    public function addNumber($num) {
        $this->numbers += $num;
        return $this;
    }

}

$a = new A();
$a->addNumber(1)->addNumber(2);

addNumber is returning an instance of itself, so you can call addNumber repeatedly.

It's often the case that a method will return an instance of another object, but the same principles apply.

juco
  • 6,331
  • 3
  • 25
  • 42