得到当前的类和方法?

我正在创建一个 log 函数,它将把我的错误记录到一个文件中。

我认为它将包含发生错误的类和方法。

有没有一种方法可以记录错误发生在哪个类和方法中,这样我就不用每次都手动键入了?

62970 次浏览

get_called_class() get's the current class. This might also be interesting: debug_print_backtrace().

I'm not big on PHP but I believe it has "magic constants" similar to C/C++. Take a look here: This seems to indicate you could use

__LINE__, __FILE__, __FUNCTION__, __CLASS__, and __METHOD__

use the __METHOD__ constant in PHP5

In the event you’re in a parent / base class, __CLASS__ will return the parent / base class name which is not desired. In that event you can use get_class():

get_class($this)

In current PHP versions (5.5+) you should use static::class

It works both in static and instance methods and returns the actual class name, even if the method body was defined in a superclass.

In Laravel 5 CLASS was returning namespace and class name, so it was a large string. So this is how you get current Class without all that other stuff:

echo (new \ReflectionClass($this))->getShortName();

Since PHP 8.0 there is new way if variable is an object:

$object::class


$this::class