开发者

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

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?


Unfortunately, PHP does not have any kind of macros. You could implement these yourself by running a command line tool like sed over some input to insert macros, but that is error prone and a bit sloppy.

To do what you want to do, you might consider the debug_backtrace function.


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.


Nope. Use a stack trace: debug_backtrace(). You can retrieve the file and line of the caller, by simply looking at the second row in the returned array.


Unfortunately there is no C like Macros in PHP.

reading a debug_backtrace is tricky and I don't like that.

What I would like to throw an exception at error points then exception object it self contains the stack trace as well as the line number and file it's coming from.

catch (Exception $e)
{
   $errorMessage  = $e->getMessage() . " LINE: " .$e->getLine(). " FILE: " . $e->getFile();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜