Get current class and method?

Php

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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__

Solution 2 - Php

In the event your in a parent / base class, http://php.net/manual/en/language.constants.predefined.php#constant.class">`__CLASS__`</a> will return the parent / base class name which is not desired. In that event you can use http://php.net/manual/en/function.get-class.php">`get_class()`</a>;:

get_class($this)

Solution 3 - Php

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.

Solution 4 - Php

use the __METHOD__ constant in PHP5

Solution 5 - Php

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

Solution 6 - Php

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

Solution 7 - Php

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

$object::class

$this::class

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionajsieView Question on Stackoverflow
Solution 1 - PhpAntony WoodsView Answer on Stackoverflow
Solution 2 - PhpSeanDowneyView Answer on Stackoverflow
Solution 3 - PhpTobiaView Answer on Stackoverflow
Solution 4 - PhpKenView Answer on Stackoverflow
Solution 5 - PhpThomas MüllerView Answer on Stackoverflow
Solution 6 - PhpMarcelo AgimóvelView Answer on Stackoverflow
Solution 7 - PhpJsowaView Answer on Stackoverflow