I was wondering how I could do this type of functions, or rather how to create a class or whatever is required to be able to execute the functions in the following way:
$var->metodo1($args)->metodo2($args)->metodo3($args);
Under what I assume from the code above, is that the result of method1 is used by method2 and the result of it is used by method3 .
I don't know what that kind of organization is called, that's why I ask the question this way. I have seen very similar code in Laravel .
I don't know if I'm wrong, that's why I ask. I tried to google but didn't find anything.
The "arrows" refer to an instance method (the functions that an object can invoke when it is instantiated), when applying one after another each method invoked should return an object, with an example it may be better understood:
It throws an error since since it
devolverNumeroAlCuadrado()
returns a number, when callingotroMetodo()
we are saying something like this:And number 4 doesn't have that method. Therefore, if we want to call
otroMetodo()
what the previous methods return, it will have to be the same instance:Another example using two different classes:
I hope I was clear and helpful!
Cheers!
Just to add another point of view:
You can also have a class chainer, which allows you to call methods like this:
without having to modify the classes
foo
,bar
,fou
. In that case the test class instance will be created by the classEncadenador
like so:Ejemplo:
Ver Demo
Resultado:
how's it going? It seems to me that what you want to do is chain methods. This is a widely used pattern, in which the return of each method in the class that you want to chain returns the instance of the class. For example:
Then you do:
Since method 1 returns the instance ($obj), it can be chained automatically with method2. It's as simple as that.
Cheers!