php 获取当前的类和方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2140282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current class and method?
提问by ajsie
I'm creating a log function that will log my errors in a file.
我正在创建一个日志函数,它将我的错误记录在一个文件中。
I thought it will contain which class and method the error occurred in.
我认为它将包含发生错误的类和方法。
Is there a way of logging in which class and method the error occurred in so I don't have to type it manually each time?
有没有办法记录发生错误的类和方法,这样我就不必每次都手动输入?
回答by Antony Woods
回答by SeanDowney
In the event your 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():
如果您在父/基类中,__CLASS__将返回不需要的父/基类名称。在这种情况下,您可以使用get_class():
get_class($this)
回答by Tobia
In current PHP versions (5.5+) you should use static::class
在当前的 PHP 版本 (5.5+) 中,您应该使用 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.
它适用于静态和实例方法,并返回实际的类名,即使方法体是在超类中定义的。
回答by Ken
use the __METHOD__constant in PHP5
使用__METHOD__PHP5 中的常量
回答by Thomas
get_called_class()get's the current class. This might also be interesting: debug_print_backtrace().
get_Called_class()获取当前类。这也可能很有趣:debug_print_backtrace()。
回答by Marcelo Agimóvel
In Laravel 5 CLASSwas returning namespace and class name, so it was a large string. So this is how you get current Class without all that other stuff:
在 Laravel 5 CLASS返回命名空间和类名,所以它是一个大字符串。所以这就是你如何在没有所有其他东西的情况下获得当前类:
echo (new \ReflectionClass($this))->getShortName();

