Cannot Use Dynamic Class Name

It seems I’ve discovered a new kind of PHP error that isn’t documented anywhere on the web yet. Here is a simple example and explanation to help correct your code.

class MyClass {}
$obj = new MyClass;
$test1 = MyClass::class;    // Right
$test2 = get_class( $obj ); // Right
$test3 = $obj::class;       // Wrong

That last line in my code sample produces the following error in PHP 7.4.

Fatal error: Cannot use ::class with dynamic class name in […][…] on line 5

This is the PHP way of saying that you have to switch to the get_class() function when retrieving the fully qualified class name of an object.

Note: An existing RFC proposes to change this behavior in PHP 8, so this particular error message might not exist in some future versions.

One thought on “Cannot Use Dynamic Class Name”

Leave a Reply

Your email address will not be published. Required fields are marked *