如何在字符串 [PHP] 中使用编译时间常量 __LINE__

How can I use the compile time constant __LINE__ in a string [PHP]

我有一个 PHP class 文件,我需要使用 __ CLASS __ , __ LINE __ 很多地方都是常量。我不想在每个地方都写这些牵引常量,所以我在 class 文件中创建了名为 log_suffix() 的方法并使用该方法。

function detail(){
    $leave_groups = LeaveGroup::get_leave_group_details($this->company_id, 1, true); 

    if($this->debug){
        print_r($leave_groups->toArray());
    }

    if($leave_groups->count() === 0){
        Log::error("log: " . $this->log_suffix() );// Line 39
        return false;
    }

    return $leave_groups;
} 

function log_suffix(){
    return "$this->company_code | $this->company_name \t on File: ". _CLASS_. "\t". __LINE__ ; // Line no 51
}

问题是,它正在打印第 51 行(行常量写入行)。

是否可以根据分享的图片得到39的编译时行号

我知道通过 try catch exception 我们可以做到这一点(获取文件和行号)。 有没有其他方法可以解决这个问题。

here is online editor link

根据magic constants documentation__LINE__ 包含“文件的当前行号”,即使用它的行。因此,查看发布的示例,在 log_suffix() 函数中它总是打印 51,无论在哪里调用此函数。
您可以在调用此函数时将 __LINE__ 作为参数传递,因为它将保存实际调用该函数的行号,但这是您要避免的。

另一种可能是在log_suffix()中使用debug_backtrace()函数,参数limit = 1。它将return一个带有一个键的数组,其值是一个数组。 'line' 键保存前一个调用范围的行。

一个简单的例子:

$debugTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1);
$callerLine = $debugTrace[0]['line'];