Toskan Toskan - 3 days ago 5
PHP Question

Why undefined variable when using function() use($var){}?

$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?

Answer

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');
Comments