The answer as always Depends.
Before deciding whether or not you need a variable you have to understand why you want the object. The goal of a variable is to store a reference to an object or value so that you can use it later, in this sense if there is no need to use it later you don’t need to store it in a variable (or constant).
In this example you gave we see a fluid interface, we give this name to classes whose methods return a reference of itself or a new instance of it, allowing to invoke a method upon the return of the method.
An example of this can be found in the PSR-7 specifications, where as you invoke the methods to build an http message (e.g. Request) you receive a new instance of that class and can chain calls.
This type of behavior is also common in the Builder project pattern, where a Builder returns to itself until a construction method (e.g. make, build or create) is called by returning what the Builder builds.
The main points where you don’t need to have a reference in a variable are:
- You will create the object only to call a method, e.g..
(new Logger("Startup"))->log("mensagem");
In this example we assume that we will not need this instance of logger after using it, if we needed we could store its reference in a variable.
- You will pass an object as a parameter once you create it.
$client->send(new User("João"));
In this example if the object is simple and the reading is not compromised you can instantiate the direct object in the method call.
An important point to remember is that you’re not programming for the computer to understand, you’re programming so that humans (you and whoever else is going to maintain this code) understand what’s been programmed, then you should try to make your code readable whenever possible, if it requires creating variables, create.
If you were making code for machines only you could name all your variables with varNumer, ex. var1, var2, var3, var4, etc., since the machine would understand, giving names that mean something is something we do so that we developers can understand what the program does with as little cognitive effort as possible.
I see no advantages, only the disadvantages in which you completely lose your object, which can make it difficult to maintain the code and debug operations, not to mention that, in my view, it impairs the readability of the code.
– Woss
i agree with @Woss, maybe it makes sense to use an instance that will only do an operation maybe, but in this example makes 3, it would make more sense to have the variable and help in debug tbm
– Ricardo Pontual
If you are not using variable it is almost certain that you also did not need a class.
– Maniero
I get it. Although it works, Phpstorm gives a Warning saying that my Function is not VOID, and even if I define them as method():void, Phpstorm removes Warning but fails to provide the class and method HINTS...
– EvandroPH