Is there any way to carry down a PHP magic constan

2019-09-19 00:59发布

问题:

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);
}