5

i wonder how php can achieve like below function design:

Class->func()->func()

Here is the laravel validate example.

    $validator->after(function($validator) 
    {
        if ($this->somethingElseIsInvalid()) 
        {
            **$validator->errors()->add('field', 'Something is wrong with this field!');**
        }
    });

Is the after() do the magic work here?

And how to create my own code that can behave like this.

2
  • 1
    In your methods you can do return $this; which returns the object and gives you the possibility to do class->func()->func()->func() Commented Sep 15, 2016 at 6:43
  • @Neat thanks and it's call method Chaining, learn somethings new today : ) Commented Sep 15, 2016 at 6:57

2 Answers 2

5

Its called Method Chaining.

Method chaining works because a function or a method of the class always returns object which further call another function.

Basically it returns it self.

Ex:

public function method1() {
    // method content ...
    return $this;
}

public function method2() {
    // method content ...
    return $this;
}

Please refer the following link to read more on Method Chaining,

http://www.techflirt.com/tutorials/oop-in-php/php-method-chaining.html

There will be more articles you could find on this.

Sign up to request clarification or add additional context in comments.

2 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
@limonte, Thanks for the comment. I updated my answer. Your comments are most welcome!
3

You need to return the object you want to chain the next method to.

public function chain() {
    return $this;
}

Sometimes this will be the current class ($this), somethings this will be an instance of another class depending on what is appropriate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.