1
$isac_start = microtime(true);

function ilog($m) use ($isac_start){

  $time_elapsed_secs = microtime(true) - $isac_start;
  file_put_contents(__DIR__.'/debug_log.txt', $m . " - time elapsed: " . $time_elapsed_secs . "\n", FILE_APPEND | LOCK_EX);
}

gives me

undefined variable $isac_start;

why? how to fix it?

Toskan
  • 11,184
  • 12
  • 75
  • 144
  • 1
    I'm pretty sure that PHP's `use` syntax is only valid on anonymous functions. I have no idea why that's the case; I find it disconcerting that named and anonymous functions are treated so differently… – Chris Nov 30 '16 at 16:50

2 Answers2

3

The use keyword is intended to be used with closures (see example 3), it is not intended to be used with regular functions. The following demonstrates correct usage:

$isac_start = microtime(true);

$ilog = function ($m) use ($isac_start) {
    var_dump($m);
    var_dump($isac_start);
};
$ilog('hello');
mister martin
  • 5,746
  • 3
  • 24
  • 58
2

use isn't applicable to named functions, only to anonymous functions. In order to get $isac_start into the function scope, you should probably just pass it as an additional argument, as in:

function ilog($m, $isac_start) { ...

use exists in order for anonymous functions to be able to inherit variables from the parent scope, which isn't really necessary for normal user-defined functions.

Don't Panic
  • 37,589
  • 9
  • 55
  • 71