Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call two method with single line in php?

Tags:

php

laravel

I have seen in Laravel calling multiple method in the single line, example:

DB::get('test')->toJson();

I have a cool class and view method in that class.

$this->call->view('welcome')->anotherMethod();

I would like to call another method also? Where should I make that method?

like image 604
user3501409 Avatar asked Jan 28 '26 12:01

user3501409


1 Answers

DB::get() seems to be a method returning an object, where you can call other functions (I think a result object of a database query). If you want to call multiple functions on one object in one line, you have to return $this in your functions, e.g.:

class View {
    public static function factory {
        // The question is: How useful is this factory function. In fact: useless in
        // the current state, but it can be extended in any way
        return new self;
    }

    public function one() {
        // do something
        return $this;
    }

    public function two() {
        // do something
        return $this;
    }
}

Then you can do:

$class = new View();
$class->one()->two();
// it's also possible to use the `factory` function
// you should think about, how useful this approach is in your application
$class = View::factory()->one()->two();

That's how you can do it in php, if laravel has some helpers for that, i can't say :)

like image 179
Florian Avatar answered Jan 30 '26 13:01

Florian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!