Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create PHP method linking?

I've seen other objects that do this:

$obj->method1()->method2();

How do I do that? Is each function just modifying the pointer of an object or returning a pointer?

I don't know the proper term for this style -- if anyone could help me with that, it would be great.

like image 948
Kerry Jones Avatar asked Apr 10 '26 20:04

Kerry Jones


2 Answers

This is achieved by returning $this at the end of each function, thus giving a chainable reference.

class MyClass {
    public function method1() {
        //...
        return $this;
    }
    public function method2() {
        //...
        return $this;
    }
}
like image 79
Lotus Notes Avatar answered Apr 13 '26 11:04

Lotus Notes


Fluid interface.

Simply set your object's method1() to return $this

like image 35
Mark Baker Avatar answered Apr 13 '26 10:04

Mark Baker



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!