Difference between ::class and get_class

Classnames aren't case sentive in PHP.

It seems like get_class($obj) returns true classname (in PHP core) and ::class returns the classname used in user's code.

<?php
// PHP 5.5
var_dump(get_class(new DaTeTImE())); // string(8) "DateTime" 
var_dump(DaTeTImE::class);           // string(8) "DaTeTImE"

// From PHP Team : The '::class' construct is done purely at compile time, based of the apparent classname passed in. It does not check the spelling of the actual class name, or even that the class exist

<?php
echo dAtEtImE::class; // Output is "dAtEtImE"
echo ThisDoesNotExist::class; // Output is "ThisDoesNotExist"

Another point is get_class takes instance as argument and ::class operate on Class definition directly without initializing any instance. You might want to get the class name without creating instance occasionally.

Tags:

Php