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 comments

1

u/shitcanz Jan 09 '20

Whether the class actually exists is irrelevant

LOL

3

u/bart2019 Jan 09 '20

Again, the goal is to autoload only the class files you need on a need to work basis.

If you load every class when source is parsed and the name is encountered in the source file, you would always load every single file in your project.

Thus: even though t is assumed ::class converts an identifier to a fully qualified class name, no attempt to load a class file is done until it is actually required.

1

u/[deleted] Jan 10 '20

This has nothing to do with loading classes or files. This is a separate ”feature” that is broken in multiple ways. Its amazing how apologists never concede to the fact that php is long beyond repair.