F
F
fsgdoterr2021-09-23 23:33:59
PHP
fsgdoterr, 2021-09-23 23:33:59

How to call class methods sequentially?

I'm new to php, now I'm trying to make a micro framework, before that I already worked with Laravel and wrote this function call:
Route::get(...)->name(...);
And I can't figure out how to make a function call sequentially, that is:

$obj = new T();
$obj->firstfunc()->secondfunc()...;

I understand that these functions should be in the same class, but when I write these functions, nothing works:
class T {
 public function firstfunc() {
    echo 'hello ';
 }
 public function secondfunc() {
   echo 'world ';
 }
}

$obj = new T();
$obj->firstfunc()->secondfunc();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2021-09-23
@fsgdoterr

For chaining, each method must return $this.

class Foo
{
    public function firstfunc()
    {
        echo 'hello ';
        return $this;
    }

    public function secondfunc()
    {
        echo 'world ';
        return $this;
    }
}

$obj = new Foo();
$obj->firstfunc()->secondfunc();

Static methods must return a new instance of the class.

A
Alexandroppolus, 2021-09-23
@Alexandroppolus

return this , or whatever it is called in PHP

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question