Static variable for optimization

optimization, php, static-variables

Solution

I find it easier to do something like the code below. That way the caching is done globally instead of per implementation of the function.

function moderatelyExpensiveFunctionCall()
{
   static $output = NULL;
   if( is_null( $output ) ) {
     //set $output
   }
   return $output;
}

Problem

I'm wondering if I can use a static variable for optimization: ``` public function Bar() { static $i = moderatelyExpensiveFunctionCall(); if ($i) { return something(); } else { return somethingElse(); } } ``` I know that once `$i` is initialized, it won't be changed by by that line of code on successive calls to `Bar()`. I assume this means that `moderatelyExpensiveFunctionCall()` won't be evaluated every time I call, but I'd like to know for certain. Once PHP sees a static variable that has been initialized, does it skip over that line of code? In other words, is this going to optimize my execution time if I make a lot of calls to `Bar()`, or am I wasting my time?

Original source