PHP多对象函数调用 [英] PHP multiple object function calls

查看:58
本文介绍了PHP多对象函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题.

This maybe a silly question.

我试图了解如何进行这些系列的对象调用. Laravel雄辩方法的例子 http://laravel.com/docs/eloquent

I am trying to understand how these series of object calls are made. Example in Laravel eloquent method http://laravel.com/docs/eloquent

$affectedRows = User::where('votes', '>', 100)->update(array('status' => 2));

我正在尝试创建一个自定义框架,并且我喜欢Laravel框架的想法. 有人可以告诉我这是什么以及如何实现这一目标.

I am trying to create a custom framework, and i like the idea of the Laravel framework. Can someone please tell me what it is and how to achieve this.

推荐答案

这称为方法链接,是通过返回对类($ this)或这些函数中另一个类对象的引用来完成的.然后,您可以在返回的对象上调用方法.

this is called method chaining and is done by returning a reference to the class( $this ), or another class object from those functions. Then you can call a method on the returned object.

这是一个简单的例子.

class foo{
     protected $_bar;

     public function bar($value){
          $this->_bar = $value;
          return $this;
    }


   public function out(){
        echo $this->_bar;
   }
}

$a = new foo();
$a->bar('hello')->out();

输出:

'hello'

仅需解释一下,上面的代码$a->bar('hello')->out();大致等同于执行此操作:

Just to explain a bit more, the above code $a->bar('hello')->out(); is roughly equivalent to doing this:

 $a = new foo();
 $b = $a->bar('hello');  //$a and $b are the same instance of the object
 $b->out();

现在,因为bar()返回$this,我们可以像上面一样将其分配给$b,然后调用out().但是$a$b都引用foo对象的相同实例,因为我们从bar()返回了$this.因此,不需要这个额外的虚假"变量,因为我们可以直接在下一次调用中引用返回对象.该方法适用于从方法返回的任何对象(不仅是$ this),但是显然,链中的下一个调用是针对返回的对象的.

Now because bar() returns $this we could assign it to $b like above and then call out(). But $a and $b both reference the same instance of the foo object, because we returned $this from bar(). So there is no need for this extra "spurious" variable as we can just reference the return object directly for the next call. This works with any object that is returned from a method (not just $this), but obviously then the next call in the chain is against the returned object.

这篇关于PHP多对象函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆