Difference between ::class and get_class

后端 未结 3 1946
死守一世寂寞
死守一世寂寞 2021-01-11 19:38

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



        
相关标签:
3条回答
  • 2021-01-11 20:20

    There is no difference, this is just two coding styles.

    0 讨论(0)
  • 2021-01-11 20:22

    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.

    0 讨论(0)
  • 2021-01-11 20:30

    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"
    
    0 讨论(0)
提交回复
热议问题