Home > Software engineering >  how to create class like laravel to call class methodes consecutive
how to create class like laravel to call class methodes consecutive

Time:12-17

hello guys its question for me to how write some class like laravel . i think this type of class more easy to use code example :

ClassName::method1('value')->method2('value')->method3('value');

if you attention methodes are use Continuous

i seen this kind of class in in laravel on route part so i have interested in this class i want to yuse it in my own programs !

is this way effective on loading ?

i will be happy to help with a example if you can explain it

thank you.

CodePudding user response:

The following example might help with the concept of method chaining.

Methods one(), two() and three() each set a property, before returning the current object, using return $this.

Returning $this (the object) allows the chaining of methods, as you can call another method on the returned object:

<?php
class Movie
{
    private string $one = '';
    private string $two = '';
    private string $three = '';

    public function one(): object
    {
        $this->one = "One ";
        return $this; // return object
    }

    public function two(): object
    {
        $this->two = "Flew Over the ";
        return $this; // return object
    }

    public function three(): object
    {
        $this->three = "Cuckoo's Nest";
        return $this; // return object
    }

    public function show(): string
    {
        return $this->one . $this->two . $this->three;
    }

}

$movie = new Movie();
echo $movie->one()->two()->three()->show();

See it in action

  • Related