Q:

Which of these is best practice for getting values from a function within a class in PHP?

I have this function in a class:
my_class::my_function()

It returns 5.
If I do this:
$total = $something + my_class::my_function();
$total2 = $something2 + my_class::my_function();
$total3 = $something3 + my_class::my_function();

Is it any less efficient than doing:
$something_else = my_class::my_function();

$total = $something + $something_else;
$total2 = $something2 + $something_else;
$total3 = $something3 + $something_else;

A:

TL;DR
Do what is right from the architectural point of view, and forget trying to do micro optimisation yourself. If you want the same value in all calculations, cache the value.
Explanation.
There is an overhead to calling any function in PHP. When you invoke a function, PHP must create a stack frame in memory, which contains information about the call, such as the parameter values, location in the code, etc. This takes some time to do, and also will take up some memory. The amount of memory this takes varies, but is usually not a lot, due to the fact that PHP passes objects by reference, and copy-on-write mechanics. So, unless you are modifying large string/binary data in your function, the overhead should be negligible. Nevertheless, you should use the second approach, i.e. the one that "caches" the value, because from the PoV of the consumer, under no circumstances is my_function() guaranteed to return the same value every time.
Year by year, PHP is more and more optimized. Examples include zVal and opcache. These improvements result in automatic optimization of sane instructions. Trying to tinker with this may actually result in PHP being unable to optimize your program. Very knowledgeable and capable people are working on this, and you do not need to do anything special to benefit from automatic optimization. Instead, focus on the architecture, and the conceptual accuracy of your code, on its normalization. Compilers are optimized more and more, hardware becomes better and cheaper every year, without your involvement; but your code will not normalize itself on its own.

