Is there any way to carry down a PHP magic constant as a function default?

a 夏天 提交于 2019-12-12 03:55:41

问题


The idea here is to create a method for logging and debugging purposes, that doesn't require passing said method the associated 'magic constants'.

Effectively, I'm trying to achieve this using a method definition like so:

function Debug($Message,$File=__FILE__,$Line=__LINE__)
{
...
}

The problem I am running in to is that if I define the above method in a file other than the one I am 'debugging', I end up with the file and line from the file the method is defined in, rather than the one I am 'debugging'.

Consider the following set of files:

Debugging.php

<?
function Debug($Message,$File=__FILE__,$Line=__LINE__)
{
    echo("$File ( $Line ) :: $Message");
}
?>

Testing.php

<?
Debug("Some message");
?>

Output:

Debugging.php ( 1 ) :: Some message

When the invocation of the message occurred in the second file - which, as should be clear by this point, isn't the intended implementation. I could of course pass the 'Debug' method those magic constants at the time of invocation, but I'm looking to eliminate unnecessary code if possible.


回答1:


You would use the function debug_backtrace like so.

function Debug($Message)
{
    $backtrace =  debug_backtrace();
    echo($backtrace[0]['file'] .'(' . $backtrace[0]['line']  . ') :: ' . $Message);
}


来源:https://stackoverflow.com/questions/40897981/is-there-any-way-to-carry-down-a-php-magic-constant-as-a-function-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!