Using ::class on objects in PHP 8.0

Using ::class on objects in PHP 8.0

Since PHP 5.5, we can use the special ::class constant which allows getting a fully qualified name (FQN) of the class by using ClassName::class syntax.

Let's say we have a User class under App\Entity namespace.

User.php

<?php

namespace App\Entity;

class User {}

So we can get an FQN of the class by using User::class.

main.php

<?php

require_once 'User.php';

use App\Entity\User;

echo User::class;

Example will output:

App\Entity\User

In versions prior to PHP 8.0, in order to get an FQN of the class of an object, we had to call the get_class function.

main.php

<?php

require_once 'User.php';

use App\Entity\User;

$user = new User();
echo get_class($user);

Since PHP 8.0, we can use the special ::class constant on objects. We will get the exact same result as using a get_class function.

main.php

<?php

require_once 'User.php';

use App\Entity\User;

$user = new User();
echo $user::class;

Leave a Comment

Cancel reply

Your email address will not be published.