What is ::class in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5.

Documentation: http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name

It’s very useful for 2 reasons.

  • You don’t have to store your class names in strings anymore. So, many IDEs can retrieve these class names when you refactor your code
  • You can use the use keyword to resolve your class and you don’t need to write the full class name.

For example :

use \App\Console\Commands\Inspire;

//...

protected $commands = [
    Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];

Update :

This feature is also useful for Late Static Binding.

Instead of using the __CLASS__ magic constant, you can use the static::class feature to get the name of the derived class inside the parent class. For example:

class A {

    public function getClassName(){
        return __CLASS__;
    }

    public function getRealClassName() {
        return static::class;
    }
}

class B extends A {}

$a = new A;
$b = new B;

echo $a->getClassName();      // A
echo $a->getRealClassName();  // A
echo $b->getClassName();      // A
echo $b->getRealClassName();  // B

Leave a Comment