函数名($param, $line = __LINE__, $file = __FILE__) {};
是否可以让一个函数自动包含行号和调用该函数的文件,
就像我在函数中调用 __LINE__
或 __FILE__
一样,它将使用函数定义所在的行和文件。
但我不想每次都将 __LINE__ 和 __FILE__ 传递到函数中。
因此,如果我将它们设置为默认参数,它们是来自函数定义还是从哪里调用?
Is it possible to have a function automatically contain the line number and the file that the function was CALLED in,
as if i call __LINE__
or __FILE__
in the function it will use the line and file the function definition is in.
but i dont want to have to pass __LINE__
and __FILE__
into the function every time.
so if i set them as the default params, do they come from the function definition, or where it is being called from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
按照你的建议做似乎不起作用。
你可以这样做,但我不确定你为什么要这样做,并且没有更好的方法来实现你想要实现的目标 - 请参阅 Wrikken 的回答。
Doing what you suggest doesn't seem to work.
You can do it like this, but I'm not sure why you want to do it and that there isn't a better approach to what you are trying to achieve - see Wrikken's answer.
唯一的方法是使用
debug_backtrace()
,但正如名称所示:用于调试。您的代码不应该根据调用的位置/时间在生产中附加任何含义或功能。The only way would be using
debug_backtrace()
, but as the name says: it is for debugging. Your code should not attach any meaning or functionality in production based on where/when it's called.虽然已经很晚了,但也许有用,您可以使用 get_called_class() 作为被调用类的名称,并且不要像插入 CLASS 的参数一样传递。
It's so late but maybe can be useful, you can use get_called_class(), for the name of class who is called, and do not pass like a parameter insted of CLASS.
如果您想在某种错误消息中使用此信息,有一个函数
trigger_error()
会引发 PHP 本机错误,因此,它将以通常的 PHP 方式显示 - 带有文件名、行号和提供的文本。该函数最简洁的功能是根据当前错误处理设置进行操作:
将直接打印出来以屏幕显示这样的错误消息:
对于开发非常方便
而此代码
将被放入错误日志中以供将来参考
生产时必须的
if you want to use this information in some kind of error message, there is a function
trigger_error()
which will raise PHP native error, so, therefore, it will be shown in usual PHP manner - with filename, line number and supplied text.Most neat feature of this function is behaving according to current error handling settings:
will print out directly to screen an error message like this:
very handy for developing
while this code
will be put into error log for the future reference
obligatory for the production