I want to do something like this for simplifying logging operations. Any idea what I should put in for ?[1]? and ?[2]??
function log_var($var) {
$line = ?[1]?;
$var_name = ?[2]?;
$line--;
$filepath = 'log-' . date('Y-m-d'). '.txt';
$message = "$line, $var_name = $var\n";
$fp = fopen($filepath, "a");
fwrite($fp, $message);
fclose($fp);
@chmod($filepath, 0666);
return TRUE;
}
This how I’d use the function in code (numbers are assumed to be line numbers in actual code):
23 $a = 'hello';
24 log_var($a);
25 $b = 'bye';
26 log_var($b);
And this is what I want to be written to the log file:
23, a = hello
25, b = bye
EDIT
I converted Paul Dixon function a bit and added the result as an answer. The new form does even MORE than I originally hoped for. Thank you again guys!
This isn’t something you can easily do, as the function parameter is an expression which is evaluated before the function is called. Thus, the function can only see the value of that expression, and not the expression itself.
If you really want to do this, you could use debug_backtrace to find the file and line number of the caller, extract that line from the source file, then parse out the expression from the function call. Here’s a proof-of-concept:
Clearly nuts. But it works 🙂 You could of course simply pass the name in along with the variable!