Thank you for your question and for all the answers! I'll share my experience in case it comes useful for someone on this subject.
I love defining a debug function in such a way that the program, when debug flag is on, would describe to me what it's doing, and I add a lot of the logging when I write the code, as this is the time when I know best which cases can be there. Then when debug flag is off, there is almost no overhead cost except for boolean checks, since the function is called (and the parameters are evaluated) only in case debug is on.
I used it in other languages in a different way, and in PHP at first I wrote it like this:
const DEBUG_LOGGING = true;
$logdbg = DEBUG_LOGGING ?
function(...$args) {
foreach ($args as $arg) {
echo var_export($arg, true), PHP_EOL;
}
} :
null;
but then it would be in the global scope:
//this would work:
$logdbg && $logdbg($var1, $var2);
function test() {
//some code
//this wouldn't work:
$logdbg && $logdbg($var3, $var4);
//it would have to be:
global $logdbg; $logdbg && $logdbg($var3, $var4);
//other code
}
and I didn't want to add global variables, which couldn't be put under a namespace. So after checking what can be in a namespace, I defined it inside a class:
const DEBUG_LOGGING = true;
class Dbg {
public static $log = null;
public static function init() {
if (DEBUG_LOGGING) {
self::$log = function(...$args) {
foreach ($args as $arg) {
echo var_export($arg, true), PHP_EOL;
}
};
}
}
}
Dbg::init();
Dbg::$log && Dbg::$log('outside function', $var1);
function test() {
//some code
Dbg::$log && Dbg::$log('inside function', $var2, $ar3);
//other code
}
test();
but it gave me the same "uninitialized" warning this thread speaks about, and didn't work!
Thanks to this thread and Norbert Wagner's recommendation, I tried with parentheses and it worked! I didn't need to add it on the boolean check, only on the call, and now the code looks like this and works:
//the only difference with the previous snippet
Dbg::$log && (Dbg::$log)('outside function', $var1);
Dbg::$log && (Dbg::$log)('inside function', $var2, $ar3);