What is ::class in PHP?

Yada picture Yada · Jun 11, 2015 · Viewed 33.6k times · Source

What is the ::class notation in PHP?

A quick Google search returns nothing because of the nature of the syntax.

colon colon class

What's the advantage of using this notation?

protected $commands = [
    \App\Console\Commands\Inspire::class,
];

Answer

alphayax picture alphayax · Feb 6, 2017

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 exemple :

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