Knowing line and file that is running a method

Asked

Viewed 450 times

4

I want to know if it is possible to know the line and file that is running a method. For example, I have a class Log, with it I log users' logs.

Log.php

<?php
/**
* Classe de Logs
*/
class Log
{
   var $con;

   private $error, $orig;

   function __construct($userid = NULL) {
      global $con;
      $this->con = $con;
      $this->obs = '';
   }

   function SetError($error, $type = 1, $concat = FALSE, $register = TRUE){
      $this->error = ($concat ? $this->error."\n ".$error : $error);
      $this->orig = 'Arquivo: '.__FILE__."\n Linha: ".__LINE__;
      if($register) $this->RegisterLog($error);
      return FALSE;
   }

Arte.php (line 85)

  } else return $this->SetError('Não foi possível carregar os produtos.');

NOTE: THE CLASS ARTE EXTENDS THE CLASS LOG

When you entered this line, I would like the variable $this->orig had the following value:

File: C: xampp htdocs projeto app class Arte.php Line: 85

But comes the value:

File: C: xampp htdocs app project class Log.php Line: 19

Is it possible to do this? Is there any other alternative I can do?

PS.: If possible I would like to not pass this information by parameters, as it would have to touch a lot of things.

  • 1

    Firing an Exception does not solve the problem?

1 answer

7


You can do using the function debug_backtrace() :

class Caller extends Log {

    function test() {
        // Chama a função na classe log
        parent::setLog();
    }

}

class Log {
    // Metodo de log
    public function setLog() {
        var_dump(debug_backtrace());
    }

}

$caller = new Caller();
$caller->test();

Exit:

array (size=2)
  0 => 
    array (size=7)
      'file' => string '/home/edi/NetBeansProjects/zion/testes/test.php' (length=47)
      'line' => int 7
      'function' => string 'setLog' (length=6)
      'class' => string 'Log' (length=3)
      'object' => 
        object(Caller)[1]
      'type' => string '->' (length=2)
      'args' => 
        array (size=0)
          empty
  1 => 
    array (size=7)
      'file' => string '/home/edi/NetBeansProjects/zion/testes/test.php' (length=47)
      'line' => int 24
      'function' => string 'test' (length=4)
      'class' => string 'Caller' (length=6)
      'object' => 
        object(Caller)[1]
      'type' => string '->' (length=2)
      'args' => 
        array (size=0)
          empty

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

  • It seems to satisfy my problem, this function is native, right? I will test later and give a feedback.

  • Just one detail: Xdebug is not required to use this function.

  • Well observed, corrected the answer.

  • Very good was exactly what I wanted, and even better. : D Still got more details, such as class, method and etc. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.