why would there be more than one object operator in a line of code in php?

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 (eg "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...
        }
    }

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.


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.

链接地址: http://www.djcxy.com/p/58152.html

上一篇: 如何在PHP中读取google返回的数据对象

下一篇: 为什么在php中的一行代码中会有多个对象操作符?