In how far do we create variables in our methods or functions?Do we only create one when we're using the result of the variable more then one time like this?function someFunction(SomeClass $someClass) {    $thisVar = $someClass->thisVar();    doSomethingElse($thisVar);    echo $thisVar;}Or just always create one no matter how many times we're using it (for better readability)?Or just call the methods from the dependency directly like this?function someFunction(SomeClass $someClass) {    doSomethingElse($someClass->thisVar());    echo $someClass->thisVar();}
Creating variables in methods/functions
object oriented;php;dependency injection;variables
One reason for introducing a separate variable is to improve readability, assumed the real name of $someClass->thisVar() is not expressive enough. This can make sense even if the function is only called once:function someFunction(SomeClass $someClass) {    $explainingName = $someClass->thisVar();    doSomethingElse($explainingName);}Of course, if you think the function name is clear enough, this variantfunction someFunction(SomeClass $someClass) {    doSomethingElse($someClass->selfExplanatoryName());}might be fine. But even in such a case, when both function names are very long,function someFunction(SomeClass $someClass) {    doSomethingElseWithAVeryLongFunctionName($someClass->selfExplanatoryButVeryLongName());}might be considered to be less readable thanfunction someFunction(SomeClass $someClass) {     $thisVar = $someClass->selfExplanatoryButVeryLongName();     doSomethingElseWithAVeryLongFunctionName($thisVar);}When you need to reuse the value at least twice like in your examples, a reason might be that $someClass->thisVar() must be called only once because of side effects, or it should be called only once because of a noteable performance impact. A third reason might be to avoid code duplication. Think of this:function someFunction(SomeClass $someClass) {    doSomethingElse($someClass->thisVar($parameter1,$parameter2,$parameter3));    echo $someClass->thisVar($parameter1,$parameter2,$parameter3);}here $someClass->thisVar($parameter1,$parameter2,$parameter3) is repated twice, which violates the dry principle. Your second example is an edge case: it is also a violation of the DRY principle, but not a severe one, and to avoid it you have to introduce more code than it actually saves you. So it is a trade-off with no clear best solution.