76

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?

1
  • You might want to provide more information about your logger class and how you intend to call it.
    – Gordon
    Jan 26, 2010 at 15:20

7 Answers 7

103

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__
3
44

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)
1
  • 2
    This does get the child class even if you are in a method defined in the parent.
    – paullb
    Mar 19, 2014 at 5:26
13

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.

3
  • In PHP 7.1 if the method body was defined in a superclass static::class returns the superclass name
    – g4b0
    Aug 30, 2017 at 15:11
  • @g4b0 no, it does not. I just tested this script with PHP 7.1.8: class A { function f() {return static::class;} } class B extends A {} $b = new B; echo $b->f(); and it correctly prints B, even if the method was defined in A.
    – Tobia
    Aug 31, 2017 at 7:35
  • 4
    Don't forget about the difference between self and static. static will refer to the class it's called upon while self is the class it was created in. Jan 10, 2018 at 12:02
8

use the __METHOD__ constant in PHP5

6

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

1
  • You're right, I forgot the context because I've just used it tomorrow. But might be interesting anyway? Jan 26, 2010 at 15:20
5

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();
1
3

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

$object::class

$this::class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.