The difference between :: class and get_class

Can you explain the difference between get_class($instance) and ClassName::class ?

 <?php // PHP 5.5 var_dump(get_class(new Datetime())); // string(8) "DateTime" var_dump(Datetime::class); // string(8) "Datetime" with lower t 
+9
source share
3 answers

Classnames are not case sensitive in PHP.

It seems that get_class($obj) returns true classname (in the core of PHP), and ::class returns the class name used in the user code.

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

// From a PHP command: The ":: class" construct is executed exclusively at compile time, based on the seemingly passed class. It does not check the spelling of the actual class name or even that the class exists

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

Another point is that get_class takes an instance as an argument, and :: class works with the class definition directly, without initializing any instance. You might want to get the class name without periodically creating an instance.

+1
source

There is no difference, these are just two coding styles.

-4
source

Source: https://habr.com/ru/post/1237510/


All Articles