Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php call nested function

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.

like image 690
Tyler Avatar asked Sep 15 '16 06:09

Tyler


People also ask

How can I call a function inside another function in PHP?

If you want to define functions within function in PHP you can do it like this: function a() { function b() { echo 'I am b'; } function c() { echo 'I am c'; } } a(); b(); c(); You must call the parent function first, then the functions inside.

Does PHP support nested functions?

Nested functions (Aka: functions inside functions) are possible in PHP, and sometimes used in the form of anonymous functions. It is also possible to create named functions inside of other functions, just as you do in procedural PHP; but I would not recommend this.

Can a PHP function call another function?

To call a function from another file in PHP, you need to import the file where the function is defined before calling it. You can import a PHP file by using the require statement. To call the greetings() function from another file, you need to import the library.

Can we make function inside function in PHP?

You can also define a function within another function and logically this too should be a local variable but recall the rule that all functions are global. In PHP inner functions are global and hence behave in the same way as if they had been declared outside of any containing function.


2 Answers

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.

like image 195
masterFly Avatar answered Sep 21 '22 02:09

masterFly


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.

like image 44
Devon Avatar answered Sep 19 '22 02:09

Devon