Toskan Toskan - 1 year ago 75
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

why? how to fix it?

Answer Source

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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download