CodeBlanks Logo Icon CodeBlanks

Class name with ::class

PHP course · Intermediate · Lesson 38/115

Learn to get a class's fully qualified name as a string with ::class.

Fully qualified name with ::class

In PHP, writing ClassName::class returns the fully qualified name (FQCN) of the class as a string. This is especially useful in namespace-aware projects.

Example: if class User {} is defined, echo User::class; prints User. If it lives under namespace App\Models;, the output is App\Models\User.

This is commonly used in dependency injection containers, logging and debugging: instead of writing the class name by hand, you get it safely with ::class.

Where ::class is useful

::class is a practical tool. For example, when registering a class with a dependency injection container, you use User::class instead of writing the string by hand; this lets the IDE rename it safely during refactoring.

Another use: debugging. Instead of (or alongside) echo get_class($obj) . "\n"; you can write echo SomeClass::class . "\n"; to see the fully qualified class path.

Since PHP 8.0 the $obj::class syntax is also supported; it returns the same value as get_class($obj).

Exercise Print the class name with ::class

Define a User class (it can be empty: class User {}). Then print the fully qualified name with echo User::class . "\n";. (Since we use no namespace, the output is User.)

Show example solution
:class . "\n";.
Example solution:
<?php
// Define a User class and print its name
class User {}
echo User::class . "
";

Test yourself

  1. What does User::class return?

    • An instance of the User class
    • The constants of the User class
    • The fully qualified name of User as a string
    • The methods of the User class
    Show answer

    The fully qualified name of User as a string — Correct. ::class returns the fully qualified name (FQCN) as a string.

  2. Get the class name with ::class

    class User {
        public string $name;
    }
    echo ____ . "\n";
    Show answer
    class User {
        public string $name;
    }
    echo User::class . "\n";
  3. Match the ::class expressions

    User::class
    Fully qualified name (FQCN)
    $obj::class
    Object's class name (PHP 8.0+)
    get_class($obj)
    Object's class name (classic)
    App\Models\User
    FQCN under a namespace

All lessons in Intermediate