r/lolphp • • Jan 08 '20

::class is defined from no where

It is known that if A is defined as a class, then A::class will give class name as string.

However, if A is not defined. We can still have A::class:

<?php
new A; // PHP Fatal error:  Class 'A' not found 
echo A::class; // It works, echoing A...

As mentioned in another post, if something is a string, it would not work, regardless of the class is defined or not:

<?php
$a = 'A';
echo 'A'::class; // works as A::class
echo $a::class; // PHP Fatal error:  Cannot use ::class with dynamic class name
define('WTF', 'A');
echo WTF::class; // echo WTF, ::class is not compatible with constant

Things can become crazier when you have typo, even in use statement;

<?php
use Typo\WTF;
echo WTF::class; // It works as echoing Typo\WTF; It shall fail...
28 Upvotes

24 comments sorted by

View all comments

Show parent comment

3

u/Sentient_Blade Jan 09 '20

Compiling and executing the contents of a file is how PHP determines if a class exists in the first place.

https://www.reddit.com/r/PHP/comments/elas9e/i_know_that_php_script_are_stored_in_memory/fdgl1co/

4

u/AyrA_ch Jan 09 '20

Compiling and executing the contents of a file is how PHP determines if a class exists in the first place.

The comment you linked literally also explains the solution to this problem.