title: Best way to prevent PHP function from being called at once when passed as a parameter?
body: <p>Consider the following code. It features <code>ensure_default()</code> helper that assigns default value to a variable IF that variable is set to false:</p>
  
  <pre><code>function resource_intensive_lookup() {
      echo 'Running '.__FUNCTION__.'&lt;br&gt;';
      return 'default_value';
  }
  
  function ensure_default(&amp;$var, $default_value)
  {
      if (! $var) {
          $var = $default_value;
      }
  }
  
  $var = 'some_value';
  
  ensure_default($var, resource_intensive_lookup());
  print_r($var);
  </code></pre>
  
  <p>The problem is that even if <code>$var</code> is set to non-false value, <code>resoursive_intensive_lookup()</code> will still be called. I could prevent that by passing just the function name as a parameter and using <code>call_user_func()</code> within the <code>ensure_default()</code>, but such approach does not scale very well if codebase has more functions that are similar to <code>ensure_default()</code>.</p>
  
  <p>I have also tried to using a closure which prevents <code>resource_intensive_lookup()</code> from called needlessly, but unfortunatelly sets <code>$var</code> to <code>Closure Object ( )</code> instead of the <code>default_value</code> when initially $var starts out being set to false:</p>
  
  <pre><code>$closure = function () {
      return resource_intensive_lookup();
  };
  
  function resource_intensive_lookup() {
      echo 'Running '.__FUNCTION__.'&lt;br&gt;';
      return 'default_value';
  }
  
  function ensure_default(&amp;$var, $default_value)
  {
      if (! $var) {
          $var = $default_value;
      }
  }
  
  $var = false;
  
  ensure_default($var, $closure);
  print_r($var);
  </code></pre>