drus40229 2009-09-02 18:24
浏览 51
已采纳

如何获取赋予当前对象的对象的类名或文件名?

To clarify:

I'm building a Logger class that allows me to easily log messages:

lib.Logger.php:

<?php
class Logger {
    private $handle;

    public function __construct($log_name, $log_path) {

        if ( ! is_dir($log_path))
            throw new Exception('Log path does not exist.');

        if ( ! in_array(strtolower(substr($log_name, 0, -4)), array('.log', '.txt')))
            $log_name = "{$log_name}.log";

        $this->handle = fopen("{$log_path}/{$log_name}", 'a');

        $this->log('------------- Initializing ------------- '.get_parent_class($this));
    }

    // --------------------------------------------------------------------

    public function __destruct() {
        fclose($this->handle);
    }

    // --------------------------------------------------------------------

    public function log($message) {
        $time = date(DATE_RFC822);

        $log = "[{$time}] {$message}
";

        fwrite($this->handle, $log);
    }    

}

?>

And I call this using:

MyController.php:

<?php
class MyController extends Controller {
    $logger = new Logger('testlog','/path/to/logs/');
    $logger->log('Logs are fun!');
}
?>

When I initialize the object:

 $this->log('------------- Initializing ------------- '.get_parent_class($this));

I want to log the name of the object (or file) that is calling log() -- in this case, either

MyController
or
/path/to/MyController.php
.

I tried using get_parent_class(), but of course this doesn't work because Logger does not have a parent class per se.

Any ideas? thank you so much for the help!

Alex B

  • 写回答

4条回答 默认 最新

  • dpeqsfx5186 2009-09-02 18:32
    关注

    The only way to handle this implicitly is to capture the output from debug_backtrace as the others have suggested.

    If you are interested in an explicit approach, maybe this could be it

    in Logger

    public function initialize( $context )
    {
      $logMessage = '------------- Initializing ------------- ';
      if ( is_object( $context ) )
      {
        $logMessage .= get_class( $context );
      } else {
        // do something else?
      }
      $this->log( $logMessage );
    }
    

    and then

    class MyController extends Controller
    {
      public function someFunc()
      {
        $logger = new Logger('testlog','/path/to/logs/');
        $logger->initialize( $this );
        $logger->log('Logs are fun!');
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题