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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With