PHP 8.0 : Allow ::class on object instance variable
08, August 2020

From PHP 8.0, we can use ::class on object instance variables to get its fully qualified class name. Previously we used get_class($object) to achieve the same thing. And if we want to respect context dependent resolution rule and get class name, then we rely on Foo\ClassName::class

<?php

namespace FOO {

    class BAZ {}
    
    class BAR {
        public function test() {
            var_dump(BAZ::class);
        }
        
        public function test2() {
            var_dump(\BAZ::class);
        }
    }
}

namespace {

class BAZ {}

$bar = new \FOO\BAR();
$bar->test();
// string(7) "FOO\BAZ"
$bar->test2();
// string(3) "BAZ"
}

As we can see, BAZ::class has resolved to "FOO\BAZ" respecting namespace. There are other other ways like "self::class" & "static::class"

Due to this functionalities, sometimes we forget that $object::class is not supported in PHP 7 while $object::constant_name does.

<?php

class BAR {
    const CONSTANT_NAME = 'value';
}

$bar = new BAR();

##
# IN PHP <= 7.4
##
var_dump($bar::CONSTANT_NAME);
// "value"
var_dump($bar::class);
// Fatal Error: Cannot use ::class with dynamic class name

##
# IN PHP 8
##
var_dump($bar::CONSTANT_NAME);
// "value"
var_dump($bar::class);
// "BAR"
//

Just like we can access constant on object variable, the same way we can call ::class to get class name. It is just a synthetic sugar for get_class($object)


However, calling ::class on non-object variable will result into TypeError

<?php

$object = 'BAR';

$object::class;
// Fatal error: Uncaught TypeError: Cannot use "::class" on value of type string

Write comment about this article: