Abhishek Salian
Abhishek Salian

Reputation: 934

PHP multiple object function calls

This maybe a silly question.

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));

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.

Upvotes: 1

Views: 2712

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

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.

Here is a simple example.

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();

output:

'hello'

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();

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.

Upvotes: 7

Related Questions