简体   繁体   English

为什么php中的代码行中会有多个对象运算符?

[英]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. 我理解它被称为对象操作符,我可以看到它是如何使用的( 我们在PHP中使用对象运算符“ - >”在哪里? )。

I'm trying to learn what the purpose is when they are strung together like in this snippet (eg "switch($this->request->param('id')): 我试图了解它们在这个片段中串联在一起的目的是什么(例如“switch($ this-> request-> param('id')):

here's a snippet of code from a site using Kohana: 这是使用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. 它有点像嵌套函数的OOP。

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. addNumber返回自身的实例,因此您可以重复调用addNumber。

It's often the case that a method will return an instance of another object, but the same principles apply. 通常情况下,方法将返回另一个对象的实例,但适用相同的原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM