Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The get_class() alternative in PHP 8

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.

<?php

namespace Foo\Bar;

class Baz
{
    public function __construct()
    {

    }
}

$baz = new \Foo\Bar\Baz;

var_dump(get_class($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;

var_dump($baz::class); 
// 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 (including 8.1, 8.2, and 8.3), 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-digest 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.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?