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 variant
function 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 than
function 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.