1

Are the results of functions being cached internally by PHP?

Simple example:

public function calc($arg){
  return pow($arg,0.5);
}

echo calc(5) . "<br>";
echo calc(5) . "<br>";

Will PHP caculate calc() twice, or will it recognize that the argument hasn't changed and give me some kind of cached result?

ManuKaracho
  • 1,180
  • 1
  • 14
  • 32
  • 3
    Yes `PHP` will calculate it twice. – Sougata Bose Sep 10 '15 at 13:19
  • 4
    No, PHP doesn't optimize like this..... it will get executed twice.... caching function results would be very bad if your function was something like: `public function calc($arg){ static $i = 0.5; return pow($arg,$i++); }` or accessed class properties that could have been changed between calls to the method – Mark Baker Sep 10 '15 at 13:19
  • 1
    wouldn't that be an implementation detail, left to whoever writes the interpreter? – njzk2 Sep 10 '15 at 13:20
  • For this type of requirement we have if else conditions call function only when the argument is not same – Sunil Pachlangia Sep 10 '15 at 13:22
  • So basically, you're asking if php does memoization out of the box - as per comments of other developers - it doesn't do that out of the box so you will need to write that part yourself, in case you need it. – Mjh Sep 10 '15 at 13:33

1 Answers1

3

If you have opcache installed then PHP will cache the operational code, or opcode. These are the machine level instructions that PHP runs. In other words, PHP is caching how to run your function, not the results or the output of running it with a given data set.

If you want to save the value of your run, you should store the result in a variable and reference that instead of calling the function over and over

$data = calc(5);
Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100