假设我有以下情况:

File1.php

<?php
 include("作用php");
 log("test");
?>

作用php

<?php
 function log($msg)
 {
  echo "";
 }
?>

我想更改日志(log)函数,使其生成以下内容:

测试(文件:File1.php,行号:3)

那么,有没有办法获取在PHP中执行当前函数的代码的文件名和行号?

EDIT for backlog usage comments:

指数php

<?php
 include("记录器.静止的php");
 include("测试课.班php");
 new TestClass();
?>

测试课.班php

<?php
 class TestClass
 {
   function __construct()
   {
     Logger::log("this is a test log message");
   }
 }
?>

记录器.静止的php

<?php
 class Logger
 {
   static public function log($msg)
   {
     $bt = debug_backtrace();
     $caller = array_shift($bt);
     echo $caller['file'];
     echo $caller['line'];
   }
 }
?>

This example will return as file "指数php" and as line number 4, this is where the class is initiated. However, it is supposed to return the file 测试课.班php and line number 6. Any idea how to fix this?

推荐答案

可以使用debug_backtrace().

http://us3.php.net/manual/en/function.debug-backtrace.php

因此,在日志(log)函数中,可以检索调用日志(log)函数的文件名和行号.

我在日志(log)类中使用了这种方法,它大大减少了获取有意义的日志(log)数据所需的代码量.另一个好处是可读性.当与字符串混合时,魔法常数往往会变得非常难看.

下面是一个简单的例子:

function log($msg)
{
  $bt = debug_backtrace();
  $caller = array_shift($bt);

  // echo $caller['file'];
  // echo $caller['line'];

  // do your logging stuff here.    
}

Php相关问答推荐

通过激活模板在数据库中创建表

如何在搜索域名时重定向到登陆页?

WordPress插件和JSON不是有效的响应错误

如何在php网站代码中清理浏览器缓存

如何在微软图形API中使用用户S访问令牌或基于租户ID的访问令牌?

使用CODIGNITER3中的OR和AND子句进行查询

使用 secure 和 httponly 选项删除 php 中的 cookie 值得吗?

为什么从一个页面到另一个页面都找不到 JQuery,因为它们使用相同的 twig 模板?

PHP API - 本地主机中的 SSL 证书问题

htaccess 重定向子域错误的 url

VS Code 对 PHP 上从父类继承的方法报告误报

在 php 中生成 MAC ISO/IEC 9797-1

加载 Xdebug PHP 7.4.0 失败

如何将文件上传添加到 WooCommerce 结帐?

避免在 WooCommerce 中多次触发挂钩函数

PHP文件如何从CSS执行

php var_dump(1) 返回字符串(4)

在 Laravel、Vuejs 和 Inertia 中配置 TypeScript 的问题

PHP 日期格式:ISO8601 与 ISO8601_EXPANDED

是否有适用于 Windows 的真正 64 位版本的 PHP 5.6?