Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ::class and get_class

Tags:

php

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
like image 843
Fabien Papet Avatar asked Dec 06 '15 14:12

Fabien Papet


2 Answers

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"
like image 52
Robin Choffardet Avatar answered Oct 20 '22 00:10

Robin Choffardet


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.

like image 27
tom10271 Avatar answered Oct 20 '22 01:10

tom10271