如何在PHP中实现c的#def功能
嗯,我不知道这是否是我想要的。但这是我的问题:
如果出现一些错误,我会将 FILE、CLASS、FUNCTION 和 LINE 记录在文件中。为此,我正在做类似的事情:
myLog('['. __FILE__ . ']' . '[' . __CLASS__ . ']' . '[' . __FUNCTION__ . ']' . '[' . __LINE__ . ']');
问题无处不在,我必须在参数中重复该代码。如果我想改变格式,我就必须改变所有地方。
我怎样才能有这样的东西:
myLog(LOG_MSG_FORMAT);
使用 PHP 定义这是不可能的,因为它会给我该定义所在位置的行号,而不是使用该定义的位置。
欢迎任何对此问题的解决方案。我并不讨厌拥有类似 C 语言的 #def 功能。
编辑: 该函数不一定仅在出现错误时才被调用。只是我想在调用该函数的任何地方记录文件、行等。 因此,如果我只是将代码粘贴到“”某处,它应该记录该行等。
例如:
<?php
...
...
<log this location>
...
...
<log this location>
Well, I don't know if thats what I want. But here is my problem:
In case of some error I am logging the FILE, CLASS, FUNCTION and LINE in a file. For that I am doing something like:
myLog('['. __FILE__ . ']' . '[' . __CLASS__ . ']' . '[' . __FUNCTION__ . ']' . '[' . __LINE__ . ']');
The problem is everywhere I've to repeat that code in the parameter. and If I want to change the format, I've to change everywhere.
How can I have something like:
myLog(LOG_MSG_FORMAT);
With PHP define it is not possible since it will give my the LINE number of the place where that definition is, not where the definition is getting used.
Any solution to this is welcome. I am not bitchy about having C like functionality of #def.
EDIT:
The function does not necessarily be called only in case of errors. It is just that I want to log the the file, line, etc. wherever I am calling that function.
So if I just paste a code somewhere "", it should log the line, etc.
For example:
<?php
...
...
<log this location>
...
...
<log this location>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
debug_backtrace()
debug_backtrace()
PHP 没有像 C 那样的预处理器。但是您可以使用您自己的错误处理程序并使用已经提到的
debug_backtrace
即可获取所需信息。PHP has no preprocessor like C. But you could use your own error handler and use the already mentioned
debug_backtrace
in it to get the required information.正如其他人所说,您可以使用 debug_backtrace 来找出日志函数的调用位置。 debug_backtrace 非常不一致,因此涉及一些技巧,这里有一个例子:
作为免费的奖励,my_log 还接受 printf 风格的参数列表,例如
as others said, you can use debug_backtrace to find out the calling location of your log function. debug_backtrace is quite inconsistent, therefore there is some trickery involved, here's an example:
As a free bonus, my_log also accepts a parameter list in printf style, e.g.