Can I make a PHP "macro" (like #define) to supply parameters for function calls?

Viewed 23240

The parameters that I am talking about are __FILE__ and __LINE__ - those of the caller of the function, so that the function can use them in error reporting.

Let's say that I have two files and line 100 of file_1.php calls my_func() in file_2.php

I'd like to make that call my_func(__FILE__, __LINE__) so that if my_func encounters an error it can report it against file_1.php at line 100.

I do that since there are hundreds of calls to my_func and reporting the error to be in my_func() itself might not be informative (unless I dump the stack). And I don't want to have to manually type those two parameters a few hundred times.

In C I would do something like #define MY_FUNC my_func(__FILE, __LINE) - can I do something similar in PHP?

4 Answers

You can replicate C-like macros with the help of source file re-writing.

Write file macro.php:

<?php

$name = $_SERVER['PHP_SELF'];
$name = preg_replace('#\/#mui', '', $name);

$file = file_get_contents($name);

// get defined macros
preg_match_all('#\#macro\h+(\w+)\h+(.*)$#mui', $file, $matches, PREG_SET_ORDER);

foreach ($matches as $m) {
    // delete macro definition
    $file = str_replace($m[0], '', $file);
    // substitute macro => value
    $file = str_replace($m[1], $m[2], $file);
}

// save processed file
$new_name = '/var/tmp/' . $name . '.pr';
file_put_contents($new_name, $file);

include_once $new_name;
exit;

Now with such tool, usage is simple:

<?php

include_once "macro.php";

#macro DEBUG_INFO ;echo('<b>  DEBUG_INFO: __FILE__ : ' . __FILE__ . ';__LINE__ : ' . __LINE__ . '</b>')

echo '<br>'.(1/2); DEBUG_INFO;
echo '<br>'.(1/0); DEBUG_INFO;
echo '<br>'.(0/0); DEBUG_INFO;

When executed outputs:

0.5 DEBUG_INFO: FILE : /var/tmp/test.php.pr;LINE : 7

INF DEBUG_INFO: FILE : /var/tmp/test.php.pr;LINE : 8

NAN DEBUG_INFO: FILE : /var/tmp/test.php.pr;LINE : 9

I have strong C background and always missed C-like macros in PHP. But hopefully we can inject some sort of replacement for it.

Related