Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Function Definition in PHP - is it possible?

In JavaScript, you can use Lazy Function Definitions to optimize the 2nd - Nth call to a function by performing the expensive one-time operations only on the first call to the function.

I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function.

Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call.

$called = false;
function foo($param_1){
  global $called;
  if($called == false){
    doExpensiveStuff($param_1);
    $called = true;
  }
  echo '<b>'.$param_1.'</b>';
}

PS I've thought about using an include_once() or require_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive.

Any Ideas? or is there a better way to tackle this?

like image 212
scunliffe Avatar asked Sep 23 '08 01:09

scunliffe


2 Answers

Use a local static var:

function foo() {
    static $called = false;
    if ($called == false) {
        $called = true;
        expensive_stuff();
    }
}

Avoid using a global for this. It clutters the global namespace and makes the function less encapsulated. If other places besides the innards of the function need to know if it's been called, then it'd be worth it to put this function inside a class like Alan Storm indicated.

like image 50
dirtside Avatar answered Oct 01 '22 17:10

dirtside


Have you actually profiled this code? I'm doubtful that an extra boolean test is going to have any measurable impact on page rendering time.

like image 23
John Millikin Avatar answered Oct 01 '22 17:10

John Millikin