The get_class() alternative in PHP 8

Amit Merchant · December 5, 2020 ·

If you’re working with PHP for a while, there might be a good chance that you’d be in need to fetch the class of an object. This could be mostly for debugging purposes.

So, pre-PHP 8, you could do it by using PHP’s get_class() method. Take the following for example.


namespace Foo\Bar;

class Baz
    public function __construct()


$baz = new \Foo\Bar\Baz;

// string(11) "Foo\Bar\Baz"

As you can tell, using get_class on a class object gives us the fully qualified class name (FQCN) for the particular object.

Using ::class on objects in PHP 8

Things have now been simplified in PHP 8. You can now directly use the ::class on the class object to get the FQCN of that object. For instance, in the previous example, you can use ::class instead of get_class() like so.

$baz = new \Foo\Bar\Baz;

// string(11) "Foo\Bar\Baz"

This was not possible in previous versions of PHP. The ::class keyword was only be applicable on classes to get the name of the class in form of a string.

Also note that using ::class on a string or null would throw a TypeError exception like so.

$object = null;
var_dump($object::class); // TypeError
Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!